各位高手你們好:
1.我想要在VB裡開啟Excel的某檔案(例如cmp.xls),結果以下列程式是可以完成開啟,但是想要關閉Excel卻無法辦到,請問該如何解決呢?
2.另外,Excel的檔案內容已有更改,關閉前會問是否儲存,若想要always say No,應該如何做呢?
3.下列程式若更改成pID = Shell("notepad",vbNormalFocus)就沒有問題,為什麼?
在Form1的內容:
Option Explicit
Dim pID As Long
Private Sub Command1_Click()
pID = Shell("start d:\excel\cmp.xls", vbNormalFocus)
End Sub
Private Sub Command2_Click()
Dim hWnd As Long
hWnd = FindProcessWindow(pID) '主要是用來找到所要的pID
SetForegroundWindow hWnd
PostMessage hWnd, WM_CLOSE, 0, 0&
End Sub
在Module的內容:
Option Explicit
Public Const WM_CLOSE = &H10
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Declare Function GetParent Lib "user32" (ByVal hWnd As Long) As Long
Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, lpdwProcessId As Long) As Long
Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Declare Function SetForegroundWindow Lib "user32" (ByVal hWnd As Long) As Long
Dim hWndProcess As Long
Function EnumWindowsProc(ByVal hWnd As Long, ByVal lParam As Long) As Boolean
Dim pID As Long
GetWindowThreadProcessId hWnd, pID
If pID = lParam Then
If GetParent(hWnd) = 0 Then
hWndProcess = hWnd
EnumWindowsProc = False ' 停止列舉 hWnd
End If
End If
EnumWindowsProc = True ' 表示繼續列舉 hWnd
End Function
Function FindProcessWindow(ByVal pID As Long) As Long
hWndProcess = 0
EnumWindows AddressOf EnumWindowsProc, pID
FindProcessWindow = hWndProcess
End Function