2016-11-13 135 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

相關問題