我正在尝试在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
行。那条线有什么问题?
答案 0 :(得分:5)
问题是你没有给Excel足够的时间来完成它的操作。通常DoEvents
会解决问题。另外,为了避免混淆,您可能希望将变量命名为“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
答案 1 :(得分:1)
应该是
Workbooks.Close
我还认为“工作簿”是一个保留词,你应该使用类似“wb”的东西。
Dim wb As Workbook