I’m working on a VBA macro, and I came across some pretty strange behavior.
It works fine with Application.ScreenUpdating = True, and even just fine when screen updating is off and using the VBA debugger to step through the macro.
Just running the macro with screen updating off, unfortunately, causes the Find function to fail in the following code:
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
Adding this short snippet above the call to Cells.Find solves the problem:
'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..."
Throwing up a MsgBox or prompt, etc. also allows the Find to succeed.
My question is, why do I have to wait?
I am unable to produce this behavior. See screenshot
SNAPSHOT
UPDATE:
If there are lot of things happening in your code then use
DoEventsso that the code passes control to the operating system so that the operating system can process other events.