2

私は 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..."

MsgBoxor プロンプトなどをスローすると、 も成功Findします。

私の質問は、なぜ私は待たなければならないのですか?

4

2 に答える 2

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、コードが制御をオペレーティング システムに渡して、オペレーティング システムが他のイベントを処理できるようにするために使用します。

于 2012-08-01T15:53:47.203 に答える