6

我正在尝试在 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

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

4

2 回答 2

5

问题是您没有给 Excel 足够的时间来完成它的操作。通常aDoEvents会解决问题。另外为避免混淆,您可能希望将变量命名为“wbk”而不是“工作簿”

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
于 2012-12-10T08:38:24.697 回答
1

它应该是

Workbooks.Close

我也认为“Workbook”是一个保留字,你应该使用“wb”之类的东西。

Dim wb As Workbook
于 2012-12-10T08:43:29.827 回答