vba脚本挂在Workbook.Close [英] vba script hangs at Workbook.Close

查看:104
本文介绍了vba脚本挂在Workbook.Close的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

运行时,Excel挂起,我无法停止脚本运行,只能杀死excel进程。调试它,它挂在 Workbook.Close 行。这个问题是什么?

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?

推荐答案

问题是你没有给Excel足够的时间来完成它的操作。通常一个 DoEvents 将解决问题。另外为了避免混淆,你可能想将变量命名为'wbk'而不是'Workbook'。

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

这篇关于vba脚本挂在Workbook.Close的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆