我使用Excel vba编写了一个小应用程序来更新.txt文件,当用户提交提交时,计数器会更新.txt文件,以便我们知道当前的运行编号,并跟踪每日提交。
.txt文件仅存储当前号码。 (即每次提交的当前号码+1)。
但是,我注意到当2个用户同时提交提交时会导致错误。我可以知道如何检查.txt文件是否已打开,并仅为用户锁定它?或者只允许一次更新,其余的将被阻止。
请指教,非常感谢你!
以下是为更新.txt文件而编写的代码
Sub TextFile_FindReplace(ByRef FileCount As Long)
Dim TextFile As Integer
Dim FilePath As String
Dim fileDate As String, todDate As String
Dim text As String, textline As String
FilePath = "c:\fileNoCount.txt"
todDate = Format(Now(), "dd/mm/yyyy")
TextFile = FreeFile
Open FilePath For Input As TextFile
Line Input #TextFile, fileDate
Close #TextFile
If DateValue(fileDate) <> todDate Then
Open FilePath For Output As TextFile
Print #TextFile, todDate
Print #TextFile, "1"
Close TextFile
Else
Open FilePath For Input As TextFile
Do Until EOF(1)
Line Input #TextFile, textline
text = text & textline
Loop
Close TextFile
FileCount = textline + 1
Open FilePath For Output As TextFile
Print #TextFile, todDate
Print #TextFile, FileCount
Close TextFile
End If
End Sub