我正在研究一个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
成功。
我的问题是,为什么我要等?
答案 0 :(得分:6)
我无法产生这种行为。见截图
Sub Sample()
Dim tempdate As Date, startCell As Range
Dim strdate As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
tempdate = DateAdd("d", -1, Now)
tempdate = DateSerial(Year(tempdate), Month(tempdate), 1) 'Start of the month
strdate = Format(tempdate, "Short Date")
Set startCell = ThisWorkbook.Sheets("Raw Data").Cells.Find(What:=CDate(strdate), 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."
Else
MsgBox "Found"
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
<强>快照强>
<强>更新强>:
如果您的代码中发生了很多事情,请使用DoEvents
,以便代码将控制权传递给操作系统,以便操作系统可以处理其他事件。
答案 1 :(得分:0)
我在尝试解决同样的问题时遇到了这个问题,我在运行任何.Find函数之前只需激活工作表就可以绕过DoEvents技巧。
你的代码与我的代码之间唯一押韵的是它们都使用.Find函数。也许这就是堵塞操作系统的原因。