上海迪士尼谈判:有什么方法可以在VB里杀死EXCEL的进程呢??

来源:百度文库 编辑:神马品牌网 时间:2024/05/05 12:08:57
我用VB生成一个EXCEL的表格,但打印出来以后EXCEL的进程不能正常退出,所以再生成表格的时候就会出错,有什么方法可以在VB里杀死EXCEL的进程呢??

按楼主的说法,杀死进程并不是一个好方法,只是亡羊补牢。其实你完全可以在编程中自己控制excel的死活。就是说,你必须要在创建excel对象和使用该对象之后,一定要及时释放和卸载,这样就可以避免出现这种现象。
Dim xlApp As Excel.Application
Dim xlBook As Excel.WorkBook
Dim xlSheet As Excel.Worksheet
Set xlApp = CreateObject("Excel.Application") '创建EXCEL对象
Set xlBook = xlApp.Workbooks.Open("文件名") '打开已经存在的EXCEL工件簿文件
xlApp.Visible = True '设置EXCEL对象可见(或不可见)
Set xlSheet = xlBook.Worksheets("表名") '设置活动工作表
xlSheet.Cells(row, col) =值 '给单元格(row,col)赋值
xlSheet.PrintOut '打印工作表
xlBook.Close (True) '关闭工作簿
xlApp.Quit '结束EXCEL对象
Set xlApp = Nothing '释放xlApp对象

源代码如下;自己看一下懂不懂
Option Explicit

Private Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDriectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long
Private Declare Function TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Type STARTUPINFO
cb As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Long
hStdInput As Long
hStdOutput As Long
hStdError As Long
End Type

Private Type PROCESS_INFORMATION
hProcess As Long
hThread As Long
dwProcessId As Long
dwThreadId As Long
End Type

Private Const SW_SHOW = 5
Private Const STARTF_USESHOWWINDOW = &H1

Dim hProcess As Long

Private Sub Command1_Click()
' 启动进程(记事本)
Dim stProcessInfo As PROCESS_INFORMATION
Dim stStartInfo As STARTUPINFO
stStartInfo.cb = LenB(stStartInfo)
stStartInfo.wShowWindow = SW_SHOW
stStartInfo.dwFlags = STARTF_USESHOWWINDOW

Dim strExe As String
strExe = "notepad.exe"

If 0 = CreateProcess(ByVal vbNullString, ByVal strExe, ByVal 0, ByVal 0, False, ByVal 0, ByVal 0, ByVal vbNullString, stStartInfo, stProcessInfo) Then
MsgBox "启动进程失败!"
Else
hProcess = stProcessInfo.hProcess
End If
CloseHandle stProcessInfo.hThread
End Sub

Private Sub Command2_Click()
' 结束进程
If hProcess <> 0 Then
TerminateProcess hProcess, -1
CloseHandle hProcess
hProcess = 0
End If
End Sub

Private Sub Form_Unload(Cancel As Integer)
If hProcess <> 0 Then
CloseHandle hProcess
hProcess = 0
End If
End Sub

楼上两位兄弟说的都是正确的。
1楼:用API可在内存中中断任何程序的进程。
2数:用VB调用Excel对象,实现对Excel的控制。
如果从编码的角度出发,我支持2楼兄弟的说法!