我正在编写一个VBA宏,只需打开另一个工作簿,刷新全部,保存,然后关闭。它将使用第二个工作簿重复此操作。然后它刷新并保存运行VBA代码的主工作簿。我面临的问题是,打开的两个工作簿正在使用Microsoft查询从JobBoss数据库中提取数据,并设置为在打开文件时刷新此数据。因此,文件打开,开始刷新查询数据,然后VBA代码尝试同时刷新导致错误。此外,在尝试保存和关闭数据之前,它不会等待数据完成刷新。
有没有办法在不冻结Excel应用程序的情况下延迟每个操作?
我已尝试application.wait
但Excel在此期间被冻结,并且数据在后台没有刷新,因为一旦时间结束,Excel解冻并且我仍然收到有关尝试执行操作的错误正在进行刷新。
这是我到目前为止所做的:
Sub Refresh_All()
'
' Refresh_All Macro
'
' Keyboard Shortcut: Ctrl+r
'
ChDir "Q:\Quality Control"
Workbooks.Open Filename:= _
"Q:\Quality Control\Internal Failure Log - Variable Month.xlsm"
ActiveWorkbook.RefreshAll
ActiveWorkbook.Save
ActiveWindow.Close
ChDir "Q:\Reports"
Workbooks.Open Filename:= _
"Q:\Reports\Finished-Transfer Report-variable month.xlsm"
ActiveWorkbook.RefreshAll
ActiveWorkbook.Save
ActiveWindow.Close
ActiveWorkbook.RefreshAll
ActiveWorkbook.Save
End Sub
答案 0 :(得分:1)
此代码在进入并禁用所有查询表的后台刷新后工作。
Sub Refresh_All()
'
' Refresh_All Macro
'
' Keyboard Shortcut: Ctrl+Y
'
ChDir "Q:\Quality Control"
Workbooks.Open Filename:= _
"Q:\Quality Control\Internal Failure Log - Variable Month.xlsm"
Dim endTime As Date
endTime = DateAdd("s", 2, Now())
Do While Now() < endTime
DoEvents
Loop
ActiveWorkbook.RefreshAll
endTime = DateAdd("s", 10, Now())
Do While Now() < endTime
DoEvents
Loop
ActiveWorkbook.Save
endTime = DateAdd("s", 5, Now())
Do While Now() < endTime
DoEvents
Loop
ActiveWindow.Close
ChDir "Q:\Reports"
Workbooks.Open Filename:= _
"Q:\Reports\Finished-Transfer Report-variable month.xlsm"
endTime = DateAdd("s", 2, Now())
Do While Now() < endTime
DoEvents
Loop
ActiveWorkbook.RefreshAll
endTime = DateAdd("s", 10, Now())
Do While Now() < endTime
DoEvents
Loop
ActiveWorkbook.Save
endTime = DateAdd("s", 5, Now())
Do While Now() < endTime
DoEvents
Loop
ActiveWindow.Close
ActiveWorkbook.RefreshAll
endTime = DateAdd("s", 10, Now())
Do While Now() < endTime
DoEvents
Loop
ActiveWorkbook.Save
End Sub
答案 1 :(得分:0)
检查一下,
您可能需要进行一些编辑,但我相信您会明白这一点。
Sub Button1_Click()
Dim wb As Workbook, bk As Workbook, bk2 As Workbook
Set wb = ThisWorkbook
Set bk = Workbooks.Open("Q:\Quality Control\Internal Failure Log - Variable Month.xlsm")
Set bk2 = Workbooks.Open("Q:\Reports\Finished-Transfer Report-variable month.xlsm")
With bk
.RefreshAll
.Save
.Close
End With
With bk2
.RefreshAll
.Save
.Close
End With
With wb
.RefreshAll
.Save
.Close
End With
End Sub
答案 2 :(得分:0)
尝试使用Application.Wait Now+TimeSerial(<hours>,<minutes>,<seconds>)
。每当我需要延迟代码执行时,它都适用于我。