Excel VBA Cells.Find失败,除非我使用Application.Wait。为什么?

时间:2012-08-01 15:47:28

标签: excel vba excel-vba replace

我正在研究一个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成功。

我的问题是,为什么我要等?

2 个答案:

答案 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

<强>快照

enter image description here

<强>更新

如果您的代码中发生了很多事情,请使用DoEvents,以便代码将控制权传递给操作系统,以便操作系统可以处理其他事件。

答案 1 :(得分:0)

我在尝试解决同样的问题时遇到了这个问题,我在运行任何.Find函数之前只需激活工作表就可以绕过DoEvents技巧。

你的代码与我的代码之间唯一押韵的是它们都使用.Find函数。也许这就是堵塞操作系统的原因。