2013-09-30 49 views
1

我運行一個字宏退出/重新啓動Word宏控制的Excel

  1. 初始化的Excel
  2. 退出這個詞時,用戶窗體創建在Excel
  3. 一個臨時的工作簿,終止Excel中

但是,似乎有一些殘餘的Excel實例/工作簿沒有完全關閉,因爲當我再次啓動單詞宏時,出現錯誤:462,遠程服務器機器...

在Word文檔中初始化用戶窗體:

private sub commandbutton1_click() 
    dim exc as excel.application 
    set exc as new excel.application 
    dim wb as excel.workbook 

    set wb = exc.workbook.saveas filename:="wordexc"  'creates temp workbook 
    userform1.show 
end sub 

run excel processing via a userform1 commandbutton: 

private sub commandbutton2_click() 

    excel.workbook("wordexc").close 'closes temp workbook 

    dim wb as excel.workbook 
    set wb = excel.workbook.saveas filename:="wordexc"  'this wb is for actual use 
    'i do not delete this wb after running cuz it has stored data that will be used 
    'if user cliks commandbutton2 again, it will be deleted and new wbook with new data 
    'is created 


    'processing code 

end sub 

private sub queryclose (etc...) 
    'Close Excel 
    Dim sKillExcel As String 

    sKillExcel = "TASKKILL /F /IM Excel.exe" 
    Shell sKillExcel, vbHide 

end sub 

順便說一句,我認爲這個問題是最後一部分:

Dim sKillExcel As String 

sKillExcel = "TASKKILL /F /IM Excel.exe" 
Shell sKillExcel, vbHide 

曲子,如果我停止宏和任務管理器終止EXCEL,它不't給我這個問題,如果我再次運行宏... 我 我也試過其他方法,如調用一個Excel工作簿保存在目錄而不是臨時通過createobject(「excel.application」)在一個sub,exc.quit,但我必須使用該終止代碼上面的cuz否則EXCEL仍然顯示在任務管理器中。

+0

要終止Excel兼容的,你有沒有試着用'。退出'的方法,而不是通過shell命令殺死任務? –

回答

2

除了沒有正確聲明你的對象,你沒有(如果我可以這樣說)沖洗正確的廁所。

看到這個例子(未測試)

我使用Latebinding,而不是早期的結合,使該代碼與任何版本的Excel

'~~> Define your Excel objects so that they are available 
'~~> in other userform sub procedures as well. 
Dim oXLApp As Object, oXLwb As Object 

Private Sub CommandButton1_Click() 
    Set oXLApp = CreateObject("Excel.Application") 

    '~~> Show Excel 
    oXLApp.Visible = True 

    '~~> Add a new workbook 
    Set oXLwb = oXLApp.Workbooks.Add 

    ' 
    '~~> Do some stuff 
    ' 

    '~~> Save the file 
    oXLwb.SaveAs "C:\wordexc.xlsx", FileFormat:=51 

    oXLwb.Close SaveChanges:=False 
End Sub 

'~~> Close and Quit Excel (Flush Toilet) 
Private Sub CommandButton2_Click() 
    oXLApp.Quit 
    Set oXLwb = Nothing 
    Set oXLApp = Nothing 
End Sub 
+1

oXLApp在UserForm_Initialize中聲明,因此在CommandButton1_Click或CommandButton2_Click中不可見。 –

+0

@ roryap:對。感謝您指出:)正如我上面提到的,它沒有測試。我修改了我的帖子。 –

+0

謝謝大家!不知道你可以設置這樣的單變量。完美的作品 – user2468695

1

爲什麼不做這樣的事情?基本上,您可以全局定義您的Excel對象,然後您可以稍後調用它的「退出」方法。

Private objExcel As Excel.Application 

Private Sub CommandButton1_Click() 
    Set objExcel = New Excel.Application 
    objExcel.Visible = True 
End Sub 


Private Sub CommandButton2_Click() 
    objExcel.Quit 

End Sub 
相關問題