vba 脚本挂在 Workbook.Close 上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13797367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:44:52  来源:igfitidea点击:

vba script hangs at Workbook.Close

excelvbaexcel-vba

提问by Gergely

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:

我正在尝试在 Visual Basic for Applications 中编写一个 hello world 应用程序,即修改 Excel 工作表中的单元格。这里是:

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.Closeline. What is the problem with that line?

运行时,Excel 挂起,我无法停止脚本运行,只能终止 excel 进程。调试它,它挂Workbook.Close在线路上。那条线有什么问题?

采纳答案by Siddharth Rout

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

问题是您没有给 Excel 足够的时间来完成它的操作。通常aDoEvents会解决问题。同样为了避免混淆,您可能希望将变量命名为“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

回答by Ian Atkin

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