Thursday, April 12, 2012

Excel VBA LogTracker

VBA code for generating Excel Log tracker

In module:

Sub eLoggerInfo(Evnt As String)
Application.ScreenUpdating = False
Dim counter As Long
    cSheet = ActiveSheet.Name
        If sheetExists("LoggerInfo") = False Then
            Sheets.Add.Name = "LoggerInfo"
            Sheets("LoggerInfo").Select
            'ActiveSheet.Protect "Pswd", userinterfaceonly:=True
        End If
        Sheets("LoggerInfo").Visible = True
        Sheets("LoggerInfo").Select
        'ActiveSheet.Protect "Pswd", userinterfaceonly:=True
' assigning value to counter
        counter = Range("A1")
       
        If counter <= 2 Then
            counter = 3
            Range("A2").Value = "Event"
            Range("B2").Value = "User Name"
            Range("C2").Value = "Domain"
            Range("D2").Value = "Computer"
            Range("E2").Value = "Date and Time"
        End If
        'fixing event length to 25
        If Len(Evnt) < 25 Then Evnt = Application.Rept(" ", 25 - Len(Evnt)) & Evnt
   
            Range("A" & counter).Value = Evnt
            Range("B" & counter).Value = Environ("UserName")
            Range("C" & counter).Value = Environ("USERDOMAIN")
            Range("D" & counter).Value = Environ("COMPUTERNAME")
            Range("E" & counter).Value = Now()
            counter = counter + 1
          'Deleting  records if no. of records are more than 20000
            If counter > 20002 Then
                Range("A3:A5002").Select
                dRows = Selection.Rows.Count
                Selection.EntireRow.Delete
                counter = counter - dRows
            End If
            Range("A1") = counter
            Columns.AutoFit
            Sheets(cSheet).Select
            Sheets("LoggerInfo").Visible = xlVeryHidden
            Application.ScreenUpdating = True
       
End Sub

Function sheetExists(sheetName As String) As Boolean
On Error GoTo SheetDoesnotExit
    If Len(Sheets(sheetName).Name) > 0 Then
        sheetExists = True
        Exit Function
    End If
SheetDoesnotExit:
        sheetExists = False
End Function
Sub ViewLoggerInfo()
    Sheets("LoggerInfo").Visible = True
    Sheets("LoggerInfo").Select
End Sub
Sub HideLoggerInfo()
    Sheets("LoggerInfo").Visible = xlVeryHidden
End Sub

In Thisworkbook module:


Private Sub workbook_beforeprint(cancel As Boolean)
Dim Evnt As String
Evnt = "Print"
Call eLoggerInfo(Evnt)
End Sub


Private Sub workbook_beforesave(ByVal saveasUI As Boolean, cancel As Boolean)
    Dim Evnt As String
    Evnt = "Save"
    Call eLoggerInfo(Evnt)

End Sub

Private Sub workbook_Open()
    Dim Evnt As String
    Evnt = "Open"
    Call eLoggerInfo(Evnt)

End Sub

No comments:

Post a Comment