2016-03-01 105 views
0

我試圖關閉所有的excel工作簿,當我發佈一個新的personal.xlsb或當用戶需要升級到最新版本時。下面是我的代碼關閉所有Excel工作簿,但它只是關閉PERSONAL.XLSB當其運行:關閉所有的excel工作簿(excel的幾個實例可能會打開)

Public Sub CloseAll() 

Dim wb As Workbook 



For Each wb In Application.Workbooks() 

    wb.Close True ' Or False if you don't want changes saved 

Next wb 

Application.Quit 

End Sub 

這裏是發佈代碼,也就是我的personal.xlsb複製到服務器(可能是有用的人,因此在這裏發佈)

Sub publish() 
    Call Settings.init 'Contains excelMakroVersjon="101" 

    Dim hFile As Long 
    Dim FileContents1 As String 
    Dim versionNumber As String 
    Dim strFile1 As String 


    strFile1 = "Z:\Dokumentstyring\LatestVersion\CopyMacro.bat" 

    Kill strFile1 
    Kill "Z:\Dokumentstyring\LatestVersion\PERSONAL*" 

    versionNumber = Left(excelMakroVersjon, 1) & "." & Right(excelMakroVersjon, Len(excelMakroVersjon) - 1) 

    FileContents1 = "ping -n 5 127.0.0.1 > nul " & vbNewLine _ 
     & "echo f | xcopy /f /y /z ""%APPDATA%\Microsoft\Excel\XLSTART\PERSONAL.XLSB"" ""Z:\Dokumentstyring\LatestVersion\PERSONAL_" & versionNumber & ".XLSB"" " 

    Open strFile1 For Binary As #1 
    Put #1, , FileContents1 
    Close #1 
    Shell "cmd.exe /k " & strFile1 
    Call CloseAll 
End Sub 

和這裏的代碼來檢查,如果你有樂特的版本,這也需要使用CLOSEALL方法:

Sub checkLatestVersion() 
    Dim temp, temp2 As Variant 
    Call Settings.init 
    temp = Dir("Z:\Dokumentstyring\LatestVersion\Personal*") 
    temp = Mid(temp, 8, 4) 
    temp2 = val(Replace(temp, ".", "")) 

    If temp2 > val(Settings.excelMakroVersjon) Then 
     Select Case MsgBox("Upgrade to latest Version: " & temp, vbYesNo) 
      Case vbYes 
      Shell "cmd.exe /k Z:\Dokumentstyring\LatestVersion\updateExcel.bat" 
      Call CloseAll 
      Case vbNo 
      'Do nothing. 

     End Select 
    End If 

End Sub 
+0

你可能想看看下面的Q&A,因爲我相信你的Excel運行的幾個實例:http://stackoverflow.com/questions/2971473/can-vba -reach-across-instances-of-excel – Ralph

+0

感謝Ralph,好像有很多代碼來關閉所有實例。升級算法在每次啓動excel時運行,因此沒有工作簿可以打開,發佈由我運行,並且我可以手動關閉alll,然後關閉personal.xlsb,所以這意味着我可能寧願只實現它我生成的批處理文件:'taskkill/f/im Excel.exe' – skatun

回答

1

試試這個...(請注意,以下代碼關閉了一個LSO當前Excel文件)

Dim oServ As Object 
Dim cProc As Variant 
Dim oProc As Object 

Set oServ = GetObject("winmgmts:") 
Set cProc = oServ.ExecQuery("Select * from Win32_Process") 

For Each oProc In cProc 
If oProc.Name = "EXCEL.EXE" Then 
    MsgBox "Close?" 
    errReturnCode = oProc.Terminate() 
End If 
Next 
相關問題