简体   繁体   English

vba脚本挂在Workbook.Close

[英]vba script hangs at Workbook.Close

I am trying to write a hello world application in Visual Basic for Applications, namely, to modify a cell in an Excel sheet. 我试图在Visual Basic for Applications中编写一个hello world应用程序,即修改Excel工作表中的单元格。 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. 运行时,Excel挂起,我无法停止脚本运行,只能杀死excel进程。 Debugging it, it hangs at the Workbook.Close line. 调试它,它挂在Workbook.Close行。 What is the problem with that line? 那条线有什么问题?

The problem is that you are not giving Excel enough time to finish it's operations. 问题是你没有给Excel足够的时间来完成它的操作。 Usually a DoEvents will solve the problem. 通常DoEvents会解决问题。 Also to avoid confusion, you might want to name your variable as `wbk' instead of 'Workbook' 另外,为避免混淆,您可能希望将变量命名为“wbk”而不是“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

It should be 它应该是

Workbooks.Close

I also think that "Workbook" is a reserved word and you should use something like "wb" instead. 我还认为“工作簿”是一个保留字,你应该使用类似“wb”的东西。

Dim wb As Workbook

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM