[英]Error if file already doesn't exist fso.OpenTextFile method
我正在使用OpenTextFile
方法將一些文本附加到日志文件中。
Sub saveStringToFile(filename, text)
Dim fso, f
Set f = fileSysObject.OpenTextFile(filename, 8)
f.Write text
f.Close
End Sub
如果文件已存在,它可以正常工作,但如果找不到目標文件,則會生成運行時錯誤。
是否有OpenTextFile
標志或創建新文件的替代方法,如果文件不存在則追加?
如有疑問,請閱讀文檔 :
object.OpenTextFile(filename[, iomode[, create[, format]]])
參數
[...]
創造
可選的。 布爾值,指示如果指定的文件名不存在,是否可以創建新文件。 如果創建新文件,則值為True;如果未創建,則為False 。 如果省略,則不會創建新文件。
打電話OpenTextFile
與設置為第三參數True
,以創建文件,如果它不存在:
Set f = fileSysObject.OpenTextFile(filename, 8, True)
可能不是一個很好的解決方案,雖然它做到了,我會用它,只是為了現在=)
Sub saveStringToFile(filename, text)
If fileSysObject.FileExists(filename) Then
Dim f
Set f = fileSysObject.OpenTextFile(filename, 8)
f.Write text
f.Close
Else
Set f1 = fileSysObject.CreateTextFile(filename, True)
f1.Write text
f1.Close
End If
End Sub
如果有的話,會欣賞更好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.