1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VBA: メッセージとログの作成

Last updated at Posted at 2021-03-25

処理内容を言葉で表示したい場面があります。

  • 進行状況をステータスバーに表示したい
  • 処理成功時に完了メッセージを表示したい
  • 処理失敗時にエラーメッセージを表示したい
  • 自動実行時にログを出力したい

上記を効率よく行うにはどうすればいいか迷うことがあったので、Excel VBA でサンプルを作成してみました。あまり言語を問わないことなので、他の言語でよく行われているやり方も知りたいと思っています。

log1.bas
Sub 個別処理(item, Optional ByRef msg As String)

On Error GoTo Catch:
    
    Application.StatusBar = "処理1を実行中"
    '処理1
    
    Application.StatusBar = "処理2を実行中"
    '処理2
    
    Application.StatusBar = False  'StatusBarをExcelに返す
    msg = "完了しました: " & item
    GoTo Finally

Catch:
    msg = Application.StatusBar & "にエラーが発生しました( " _
          & Err.Number & "): " & item

Finally:
    MsgBox msg  'メッセージ表示(必要な場合)

End Sub

どの段階でエラーになったかを示すために、エラーメッセージの中に
Application.StatusBar = なんとか の部分がコメント代わりになるという効用もあります。GoTo Finallyを忘れるのはよくあるミスです。上記はSubにしましたが、Functionにして成功/失敗をTrue/False で返すのもよさそうです。

呼び出し元は(ざっくりですが)下のようになります。

log2.bas
Sub 全体処理()    

    Dim msg As String, log As String    

    Dim item, items
    For Each item In items
        Call 個別処理(item, msg)
        log = log & msg & vbCrLf
    Next i   

    Debug.Print log

End Sub
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?