I am creating an error log as a text file for my application. Since it is being used by many different users, I decided to keep it logged in a specific folder (that is protected) on our network.
I have tested the code and it works, even if I have the log file open when I run the module, it still writes to the log file and saves (as long as I don't save the opened log file after the module runs)
What I am worried about is when 2 or more users are trying to write to the log file at the same time. I wanted to add something that checks if the file is open, and if it is, wait a second or two and then try to write to it again. Maybe try it a few times?
Below is my sample code.
Note that I am using the log creation in another module.
Code
Sub datatopass()
LogInformation Worksheets("Email").Range("L2").Value & "|" & _
Application.UserName & "|" & _
Worksheets("Email").Range("M2").Value & "|" & _
Worksheets("Email").Range("N2").Value & "|" & _
"other things"
end sub
'*******other module**************
Public LogFileName As String
Sub LogInformation(LogMessage As String)
'Const LogFileName As String = "\\n530fs1\PCLFileShares\pcl_reposit\Pricing_Tools\PAT\Security\" & Int(Now()) & "\PAT_APPROVALS.LOG"
Dim FileNum As Integer
Dim mdate
'get month in text
If Month(Int(Now())) = 1 Then
mdate = "Jan"
ElseIf Month(Int(Now())) = 2 Then
mdate = "Feb"
ElseIf Month(Int(Now())) = 3 Then
mdate = "Mar"
ElseIf Month(Int(Now())) = 4 Then
mdate = "Apr"
ElseIf Month(Int(Now())) = 5 Then
mdate = "May"
ElseIf Month(Int(Now())) = 6 Then
mdate = "Jun"
ElseIf Month(Int(Now())) = 7 Then
mdate = "Jul"
ElseIf Month(Int(Now())) = 8 Then
mdate = "Aug"
ElseIf Month(Int(Now())) = 9 Then
mdate = "Sep"
ElseIf Month(Int(Now())) = 10 Then
mdate = "Oct"
ElseIf Month(Int(Now())) = 11 Then
mdate = "Nov"
ElseIf Month(Int(Now())) = 12 Then
mdate = "Dec"
End If
ydate = Year(Int(Now()))
LogFileName = "\\n530fs\PTSecurity\" & ydate & "_" & mdate & "_APPROVALS.LOG"
FileNum = FreeFile ' next file number
Open LogFileName For Append As #FileNum ' creates the file if it doesn't exist
'*****around here is where I want to put the check and wait?************
Print #FileNum, LogMessage ' write information at the end of the text file
Close #FileNum ' close the file
End Sub
Display More