在Excel VB脚本中暂停执行

时间:2017-06-11 13:07:52

标签: excel vba excel-vba vbscript

我有以下脚本在Excel电子表格中运行自动更新宏,但是我需要它暂停以便在关闭之前给宏时间更新数据。我已经尝试了我在这里找到的多个解决方案,但是我找不到一个会在数据更新完成后释放电子表格以关闭并退出的解决方案。这是现在的剧本,任何想法都将受到赞赏:

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\Users\Daily Update.xlsm", 0, False)

xlapp.displayalerts = false
xlApp.Run "RefreshData"
xlApp.Wait Now + 0.007
xlapp.displayalerts = true
xlBook.Close(False)
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Echo "Daily Update Finished."
WScript.Quit

1 个答案:

答案 0 :(得分:0)

不要等待宏RefreshData完成然后关闭文件,而是在宏中执行。

我正在做的是在宏的末尾,我正在C:\MyVBSFolder\创建一个空白文本文件。用VBS文件夹路径替换路径。

Sub RefreshData()
    '
    '~~> Rest of your code
    '

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim oFile As Object
    Set oFile = fso.CreateTextFile("C:\MyVBSFolder\CloseMe.Txt")
    oFile.Close
    Set fso = Nothing
    Set oFile = Nothing

    ThisWorkbook.Close (False)
End Sub

然后像这样使用它(未经测试

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\Users\Daily Update.xlsm", 0, False)

xlApp.DisplayAlerts = False
xlApp.Run "RefreshData"

'~~> Replace the path with the vbs folder path
'~~> Check if the file was created. If it was then quit
'~~> Excel application
Do While Dir("C:\MyVBSFolder\CloseMe.Txt") = "": DoEvents: Loop

xlApp.Quit

'~~> Delete the file
Kill "C:\MyVBSFolder\CloseMe.Txt"

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Echo "Daily Update Finished."
WScript.Quit