求测试一个文件是否存在的方法

VBDN 2005-09-18 06:09:10
方法越多越好!
...全文
320 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
VBDN 2005-09-19
  • 打赏
  • 举报
回复
呵呵,其实我倾向于DIR函数。FILELEN是根据错误来判断的,FSO要使用COM对象,都不是好的办法。
唐古拉山 2005-09-18
  • 打赏
  • 举报
回复

Function FolderExist(foldername As String)
Dim Fso As New FileSystemObject
If Fso.FolderExists(foldername) = True Then
FolderExist = True
Else
FolderExist = False
End If
Set Fso = Nothing
End Function


唐古拉山 2005-09-18
  • 打赏
  • 举报
回复
引用 Microsoft Scripting Runtime

判断文件、文件夹是否存在:

'返回布尔值:True 存在,False 不存在,filername 文件名

Function FileExist(filename As String)
Dim Fso As New FileSystemObject
If Fso.FileExists(filename) = True Then
FileExist = True
Else
FileExist = False
End If
Set Fso = Nothing
End Function


northwolves 2005-09-18
  • 打赏
  • 举报
回复
Function FileExists(filename As String) As Boolean '文件存在与否
On Error Resume Next
FileExists = (Dir(filename) <> "")
End Function

Function DirExists(path As String) As Boolean '目录存在与否
On Error Resume Next
DirExists = (Dir(path & "\nul") <> "")
End Function
supergreenbean 2005-09-18
  • 打赏
  • 举报
回复
偶自己反正是这么用的
Function FileExists(ByVal sFilename As String) As Boolean
On Error Resume Next
Call FileLen(sFilename)
FileExists = Err.Number = 0
End Function

你当然也可以用Dir,GetAttr,Open filename As ...等等
Function FileExists2(ByVal sFilename As String) As Boolean
FileExists2 = Dir$(sFilename, vbArchive + vbHidden + vbNormal + vbSystem + vbReadOnly) <> ""
End Function

或者用Windows API,如PathFileExists

亦或者使用FileSystemObject的FileExists方法

总之,办法的确是有很多很多

对于那个条件编译的问题。一般大家都是通过#Const语句、工程编译对话框(也就是vb命令行参数)指定条件编译中的条件部分,而这个部分,根据说明,应该是由条件编译常数和操作符组成的。偶自己是没有找到什么资料说明为何在VB和VBA里可以在条件编译语句的条件中可以使用Len或者LenB。这个恐怕只能猜测是MS为同志们提供的一种便利吧,hoho~~~

VBDN 2005-09-18
  • 打赏
  • 举报
回复
条件编译是要用常数的
========================
为什么下边的代码能编译通过?
#If (Len("abcd") = 5) Then
Private Declare Function pickup Lib "searchmail.dll" (ByVal URL As String) As String
#Else
Private Declare Function pickup Lib "searchmail.dll" (ByVal URL As String) As String
#End If
VBDN 2005-09-18
  • 打赏
  • 举报
回复
绿豆,你这就算解决问题?
supergreenbean 2005-09-18
  • 打赏
  • 举报
回复
建议搜索一下先,有n多个先人问过这个问题,像什么Dir(filename)<>"",on error + open filename...已经真的好多了

7,762

社区成员

发帖
与我相关
我的任务
社区描述
VB 基础类
社区管理员
  • VB基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧