vba 检查目录是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45815972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 13:08:46  来源:igfitidea点击:

Check if directory exists

vbaexcel-vbaexcel

提问by

I have this piece of code, but can't make it run for it returns Bad file name or number error:

我有这段代码,但不能让它运行,因为它返回Bad file name or number error

If Dir(ws.txtFldr, vbDirectory) = "" Then
    MsgBox "Output Directory does not exist!", vbExclamation, "Error!"
    Exit Sub
End If

I just want to check if the given directory exists, if not, then prompt the message. txtFldris an activeX textbox control and wsis a worksheet. I'm actually saving it in either a shared dir or just local.

我只想检查给定的目录是否存在,如果不存在,则提示消息。txtFldr是一个activeX 文本框控件并且ws是一个工作表。我实际上是将它保存在共享目录中或仅保存在本地。

回答by Andrew Truckle

How about this:

这个怎么样:

If Len(Dir(ws.txtFldr, vbDirectory)) = 0 Then
    MsgBox "Output Directory does not exist!", vbExclamation, "Error!"
    Exit Sub
End If

Many other ways are also shown by doing a search on the internet. For example, hereit has another approach:

通过在互联网上进行搜索,还显示了许多其他方式。例如,这里它有另一种方法:

Public Function FileFolderExists(strFullPath As String) As Boolean
'Author       : Ken Puls (www.excelguru.ca)
'Macro Purpose: Check if a file or folder exists

    If strFullPath = vbNullString Then Exit Function
    On Error GoTo EarlyExit
    If Not Dir(strFullPath, vbDirectory) = vbNullString Then FileFolderExists = True

EarlyExit:
    On Error GoTo 0
End Function

Usage:

用法:

Public Sub TestFolderExistence()
'Author       : Ken Puls (www.excelguru.ca)
'Macro Purpose: Test if directory exists
    If FileFolderExists(ws.txtFldr) Then
        MsgBox "Folder exists!"
    Else
        MsgBox "Folder does not exist!"
    End If
End Sub

This second approach is using some the Errorhandling functionality available in VBA and GoTolabels to bypass code.

第二种方法是使用ErrorVBA 和GoTo标签中可用的一些处理功能来绕过代码。