我正在研究一个 VBA 宏,我遇到了一些非常奇怪的行为。
它可以正常工作Application.ScreenUpdating = True
,甚至在屏幕更新关闭并使用 VBA 调试器单步执行宏时也可以正常工作。
不幸的是,仅在屏幕更新关闭的情况下运行宏会导致Find
函数在以下代码中失败:
Application.StatusBar = "Extracting data and updating tables..."
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open FileName:=Save_folder & "new_data.xls"
Workbooks("new_data.xls").Sheets("data").Range("B9:B39").Copy
Dim tempdate As Date, startCell As Range
tempdate = DateAdd("d", -1, Now)
tempdate = DateSerial(Year(tempdate), Month(tempdate), 1) 'Start of the month
Dim strdate As String
strdate = Format(tempdate, "Short Date")
Set startCell = ThisWorkbook.Sheets("Raw Data").Cells.Find(What:=CDate(strdate), After:=ThisWorkbook.Sheets("Raw Data").Range("A1"), LookIn:=xlFormulas _
, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If startCell Is Nothing Then
MsgBox "Couldn't find a date equal to the start of yesterday's month."
Exit Sub
Else
startCell.Offset(0, 1).PasteSpecial xlPasteValues, Transpose:=False
End If
在调用上方添加这个简短的代码片段来Cells.Find
解决问题:
'Wait one second, to appease the Excel object creation gods
Application.StatusBar = "Wait one second..."
Application.Wait Now + TimeValue("00:00:01")
Application.StatusBar = "Pasting values..."
抛出一个MsgBox
或提示等也允许Find
成功。
我的问题是,我为什么要等?