'判断文件是否存在.Private Sub Command1_Click() Dim FileName As String FileName = "F:\ACA\test.txt"If Dir(FileName) <> "" Then MsgBox FileName & "存在" Else MsgBox FileName & "不存在" End If End Sub
if len(dir(filename)) then 存在 else 不存在
用FSO对象 Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.fileExists("c:\config.ini") Then msgbox "yes" Else MsgBox "Can not find config.ini" End If
在打开文件的代码之前加验证:if dir(路径+文件名)<>"" THEN 这里加打开代码 endif
Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.fileExists("c:\config.ini") Then msgbox "yes" Else MsgBox "Can not find config.ini" End If
Public Function FileExist(Filename As String) As BooleanOn Error GoTo NotExist
Call FileLen(Filename) FileExist = True Exit Function
NotExist:
End Function
添加一个按钮,一个文本框'文件打开的方法↓ private sub command1_click() dim readtext as string open "c:\try.txt" for input as #1 while not EOF(1) line input #1 , readtext text1.text=text1.text & readtext &vbcrlf wend '文件关闭的方法 close #1 '文件打开,或写入后一定要使用关闭的方法关闭文件,否则有可能造成文件丢失等错误 End Sub'以下是判断文件是否存在的代码↓ Private Sub Command1_Click() Dim FileName As String FileName = "e:\try.txt"If Dir(FileName) <> "" Then MsgBox FileName & "存在" Kill (FileName) '如果想删除它,加上这句! MsgBox "文件以删除" Else MsgBox FileName & "不存在" '如果想创建加上以下语句↓ Open FileName For Append As #1 '以不覆盖写的方式打开文件 Print #1, Text1.Text Close #1 MsgBox "文件写入完毕,请去" & FileName & "下查看" End If End Sub
建议使用on error goto的错误处理方法,虽然上面提到的方法都可以判断文件是否存在,倡忽略了其它的因素.如:使用光驱/软驱/网络硬盘时,驱动器没有准备好,此时将发生其它的错误.等等,还有许多类似的错误.因此,使用错误处理可以使程序的健壮性更好. 关于错误号和描述可以在msdn查找,举例如下52 bad file name or number 53 file not found 54 bad file mode 55 file already open 58 file already exists
Dim FileName As String
FileName = "F:\ACA\test.txt"If Dir(FileName) <> "" Then
MsgBox FileName & "存在"
Else
MsgBox FileName & "不存在"
End If
End Sub
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.fileExists("c:\config.ini") Then
msgbox "yes"
Else
MsgBox "Can not find config.ini"
End If
这里加打开代码
endif
If objFSO.fileExists("c:\config.ini") Then
msgbox "yes"
Else
MsgBox "Can not find config.ini"
End If
Call FileLen(Filename)
FileExist = True
Exit Function
NotExist:
End Function
private sub command1_click()
dim readtext as string
open "c:\try.txt" for input as #1
while not EOF(1)
line input #1 , readtext
text1.text=text1.text & readtext &vbcrlf
wend
'文件关闭的方法
close #1
'文件打开,或写入后一定要使用关闭的方法关闭文件,否则有可能造成文件丢失等错误
End Sub'以下是判断文件是否存在的代码↓
Private Sub Command1_Click()
Dim FileName As String
FileName = "e:\try.txt"If Dir(FileName) <> "" Then
MsgBox FileName & "存在"
Kill (FileName) '如果想删除它,加上这句!
MsgBox "文件以删除"
Else
MsgBox FileName & "不存在"
'如果想创建加上以下语句↓
Open FileName For Append As #1 '以不覆盖写的方式打开文件
Print #1, Text1.Text
Close #1
MsgBox "文件写入完毕,请去" & FileName & "下查看"
End If
End Sub
关于错误号和描述可以在msdn查找,举例如下52 bad file name or number
53 file not found
54 bad file mode
55 file already open
58 file already exists