当另一个应用程序将数据写入data.txt文件并且VBA尝试读取它时,这段代码显然会造成麻烦。
有没有办法忽略这些异常或更好地等待文件可以自由访问然后继续执行代码?
fileName = "C:\TEXT\data.txt"
fileNo = FreeFile 'Get first free file number
Open fileName For Input As #fileNo
Do While Not EOF(fileNo)
Line Input #fileNo, textRow
jsonText = textData & textRow
Loop
Close #fileNo
答案 0 :(得分:0)
我试过了,但我不确定它是否100%可靠:
Dim continue As Boolean
fileName = "C:\TEXT\data.txt"
fileNo = FreeFile 'Get first free file number
continue = True
Do While continue
On Error Resume Next
Open fileName For Input As #fileNo
If Err Then
continue = True
Application.Wait (Now + 0.000001)
Else
Do While Not EOF(fileNo)
Line Input #fileNo, textRow
jsonText = textData & textRow
Loop
Close #fileNo
continue = False
End If
Loop
答案 1 :(得分:0)
这是我的意思的一个例子。
fileName = "C:\TEXT\data.txt"
fileNo = FreeFile 'Get first free file number
On Error Resume Next
Do
Open fileName For Input As #fileNo
If err.number = 0 then
Exit Do
Else
Err.clear
End If
Loop
On Error Goto 0
Do While Not EOF(fileNo)
Line Input #fileNo, textRow
jsonText = textData & textRow
Loop
Close #fileNo