退出/重新启动控制excel的单词宏

时间:2013-09-30 17:36:39

标签: excel excel-vba ms-word word-vba vba

我正在运行一个单词宏

  1. 初始化Excel
  2. 在excel中创建临时工作簿
  3. 退出单词userform时,终止excel
  4. 然而,似乎有一些剩余的Excel实例/工作簿没有完全关闭,因为当我再次启动单词宏时,我收到错误:462,远程服务器机器......

    初始化word文档中的userform:

    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,如果我再次运行宏,它就不会给我这个问题... 一世 我也尝试过其他方法,比如在一个子目录中通过createobject(“excel.application”)调用我保存在目录而不是临时目录中的excel工作簿,但是我必须使用上面的终止代码,否则EXCEL仍然显示在任务管理器中。

2 个答案:

答案 0 :(得分:2)

除了没有正确宣布你的物品外,你不是(如果我可以这样说的话)正确冲洗马桶。

请参阅此示例(未测试)

我正在使用Latebinding而不是Early Binding,因此此代码与任何版本的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 :(得分: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