vba script hangs at Workbook.Close

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

I am trying to write a hello world application in Visual Basic for Applications, namely, to modify a cell in an Excel sheet. Here it is:

Sub hello()      Dim obj As Object     Dim Workbook As Object      Set obj = CreateObject("Excel.Application")     Set Workbook = obj.Workbooks.Open("C:\Users\gbuday\Desktop\Oktatás\Excel\start.xlsx")      Workbook.Worksheets("Munka1").Range("B3") = "Hello World!"      Workbook.Close     Set Workbook = Nothing     Set obj = Nothing  End Sub 

When running, Excel hangs and I cannot stop the script running, only kill the excel process. Debugging it, it hangs at the Workbook.Close line. What is the problem with that line?

回答1:

The problem is that you are not giving Excel enough time to finish it's operations. Usually a DoEvents will solve the problem. Also to avoid confusion, you might want to name your variable as `wbk' instead of 'Workbook'

Sub hello()     Dim obj As Object, wbk As Object      Set obj = CreateObject("Excel.Application")     Set wbk = obj.Workbooks.Open("C:\Users\gbuday\Desktop\Oktatás\Excel\start.xlsx")      wbk.Worksheets("Munka1").Range("B3") = "Hello World!"      DoEvents      '~~> Change True to False if you do not want to save     wbk.Close SaveChanges:=True      Set wbk = Nothing: Set obj = Nothing End Sub 


回答2:

It should be

Workbooks.Close 

I also think that "Workbook" is a reserved word and you should use something like "wb" instead.

Dim wb As Workbook 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!