본문 바로가기
엑셀쉽게

엑셀에서 VBA를 이용하여 Log 파일에 저장하는 방법(On Error GoTo 발생시 처리포함)-샘플 Excel첨부. 로그 오류

by 해피비(Happy plan B) 2022. 6. 11.
반응형

안녕하세요. 누군가에게 기댈 수 있는 곳이 되길 바라며, 함께 할 수 있는 일상 공유로 SNS에 컨텐츠를 만드는 행복랜드 행부장(HappyLandHB)입니다.

엑셀에서 VBA를 이용하여 Log를 파일에 저장하는 방법입니다. On Error GoTo 발생시 처리방법도 포함합니다.

출처: 본인

글을 보시기 전에 공감하트 클릭 부탁드립니다. (위 혹은 아래에 위치)

"합산하기" 클릭 시에 동작합니다.

아래는 VBA소스 입니다. (첨부한 엑셀에서 Alt + F11 클릭 후에 확인 가능)

'//Log 파일이름
Public g_strLogFileName As String

'//Save Log
'//Scripting Runtime Library 사용하기
'//도구-참조 클릭 후에 Microsoft Scripting Runtime 추가

Public g_objFSO As Scripting.FileSystemObject
Public g_scrText As Scripting.TextStream

Public Function LogFile_WriteError(ByVal sFileName As String, ByVal sCalledFunctionName As String, _
                                   ByVal sMessage As String)
Dim sText As String
   On Error GoTo ErrorHandler
   If (g_objFSO Is Nothing) Then
      Set g_objFSO = New FileSystemObject
   End If
   If (g_scrText Is Nothing) Then
      If (g_objFSO.FileExists(sFileName) = False) Then
         Set g_scrText = g_objFSO.OpenTextFile(sFileName, IOMode.ForWriting, True)
      Else
         Set g_scrText = g_objFSO.OpenTextFile(sFileName, IOMode.ForAppending)
      End If
   End If
   
   '//마지막에는 vbCrLf 제외
   sText = sText & ">> " & Format(Date, "yyyy.mm.dd") & " " & Format(Time, "hh:mm:ss") & vbCrLf
   sText = sText & ">> " & "호출한 함수: " & sCalledFunctionName & vbCrLf
   sText = sText & ">> " & sMessage & vbCrLf
   sText = sText & "######################################################################"
   
   g_scrText.WriteLine sText
   g_scrText.Close
   Set g_scrText = Nothing
   
   Exit Function
   
ErrorHandler:
   Set g_scrText = Nothing
   Call MsgBox("파일(" & sFileName & ")에 저장할 수 없습니다.(파일경로를 확인필요)", vbCritical, "Log저장 오류")
   
End Function

Sub cmdSum_Click()
    Dim rRange As Range
    Dim rCell As Range
    Dim iSum As Integer
    Dim sErrorMsg  As String
    Dim strFileName As String
    Dim strSubName As String
    Dim strMsg As String
    
    Set rRange = ActiveSheet.Range("B2:B6")
          
    For Each rCell In rRange
        On Error GoTo ErrorHandler:
        iSum = iSum + rCell.Value
    Next rCell
   
    ActiveSheet.Range("B9") = iTotal
   
Exit Sub
 
ErrorHandler:
    g_strLogFileName = "TEST"
    
    strFileName = "C:\temp" & "\" & "log" & Format(Date, "yyyymmdd") & "_" & g_strLogFileName & ".txt"
    strSubName = "cmdSum_Click()"
    strMsg = "Error Number: " & Err.Number
    
    MsgBox strMsg
    Call LogFile_WriteError(strFileName, strSubName, strMsg)
    Resume Next
End Sub



샘플 Excel파일을 아래에 첨부합니다. (파일을 실행하기 위해, 파일 실행 후에 "편집 사용"을 클릭해야 매크로가 실행합니다.)

(VBA)엑셀에서Log저장하는방법(by HappylandHB 행복플랜B).xlsm
0.06MB

도움이 되셨다면 공감하트 클릭 부탁드립니다. (위 혹은 아래에 위치)
감사드리며…

오늘 더 행복하시길.
감사합니다.


반응형

댓글