2016-11-13 455 views
0

当另一个应用程序正在将数据写入data.txt文件并且VBA尝试读取它时,这段代码显然会引起麻烦。Excel VBA - 例外:权限被拒绝错误70

有没有办法忽略这些异常或更好的等待,直到文件可以自由访问然后继续执行代码?

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

您等待。你是程序员,进入循环直到成功。 – 2016-11-13 22:42:15

+0

@TimWilliams这是短命的。它应该是prolly少数milisoconds。 – Totallama

回答

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 
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 
+0

Tnx的答案。不过,我已经提出了我的意见,它似乎工作正常,所以我想我会坚持。 – Totallama