1

要約:基本的なエラー処理を行いたい

問題:コードをステップスルーすると、エラーがない場合でも「エラー」ブロックデータが実行されます

-私はVBAでのエラー処理にかなり慣れていないので、コードにブロックに入るように指示する以外に、Errorブロックのコードが実行される理由がわかりません。前もって感謝します!

コード

Function getReports()

    startJournal = Sheets("Runsheet").Range("B5")
    endJournal = Sheets("Runsheet").Range("E5")

    If startJournal = 0 Or endJournal = 0 Then

        GoTo Error

    End If

    'bunch of code

Error:
    MsgBox ("Error Statement")

End Function
4

2 に答える 2

7

Exit Functionエラーラベルの前に必要です。
つまり、コードはエラーの場合にのみラベル(eh)にヒットし、それ以外の場合は終了する必要があります。

Function getReports() 
on error goto eh
    startJournal = Sheets("Runsheet").Range("B5")
    endJournal = Sheets("Runsheet").Range("E5")

    If startJournal = 0 Or endJournal = 0 Then

        GoTo Error

    End If

    'bunch of code

Exit Function

eh:
    MsgBox ("Error Statement")

End Function

あなたのコードを見て、あなたはそれを次のように書くことができます

Function getReports(startJournal as integer, endJournal as integer) as Boolean
    If startJournal = 0 Or endJournal = 0 Then
        msgbox "startJoural or endJournal should not be 0."
        exit function  '** exiting will return default value False to the caller
    End If

    'bunch of code
getReports = True
End Function

発信者側

if getReports(Sheets("Runsheet").Range("B5"), Sheets("Runsheet").Range("E5")) then
   call faxTheReport   '** This function will be called only if getReports returns true.
end if
于 2012-09-21T19:17:01.030 に答える
1

これが、VBAコードのエラーを一般的に処理する方法です。IEこれは、Internet Explorer(変数)のインスタンスを自動化するクラスのコードから取得されました。はLog、何が起こっているかをユーザーに通知するために使用されます。変数DebugUserはブール値であり、コードを実行しているときにtrueに設定します。

Public Sub MyWorkSub()

    On Error GoTo e

    Nav "http://www.somesite.com"

    DoSomeSpecialWork

    Exit Sub
e:
    If Err.Number = -2147012894 Then
        'timeout error
        Err.Clear
        Log.Add "Timed Out... Retrying"
        MyWorkSub
        Exit Sub
    ElseIf Err.Number = -2147023170 Or Err.Number = 462 Or Err.Number = 442 Then
        RecoverIE
        Log.Add "Recovered from Internet Explorer Crash."
        Resume
    ElseIf Err.Number = 91 Then
        'Page needs reloading
        Nav "http://www.somesite.com"
        Resume 'now with this error fixed, try command again
    End If

    If DebugUser Then
        Stop 'causes break so I can debug
        Resume 'go right to the error
    End If

    Err.Raise Err.Number

End Sub
于 2012-09-21T19:38:23.100 に答える