返回

Excel VBA 中如何正确检查路径是否存在?

windows

Excel VBA 中正确检查路径是否存在

问题

使用 Excel VBA 函数 GetFilePathIfExists 检查路径是否存在时,即使路径存在,该函数也可能返回错误的结果。这导致程序执行不正确,浪费时间和精力。

解决方案

要解决此问题,我们需要修改 GetFilePathIfExists 函数,以正确处理返回 0 的情况。修改后的函数如下:

Function GetFilePathIfExists(filePath As String) As String
    If Len(Dir(filePath)) > 0 Then
        GetFilePathIfExists = filePath
    End If
End Function

修改后的函数不再使用 Else 语句返回空字符串。如果路径不存在,函数直接退出,不返回任何值。这将导致函数返回 Nothing,在 VBA 中被视为 False,从而更准确地反映路径不存在的情况。

步骤

  1. 找到并修改 GetFilePathIfExists 函数,如上所示。
  2. 在你的 VBA 代码中使用修改后的函数。
  3. 现在,函数将正确识别路径是否存在,并相应地返回结果。

示例

Function GetFilePathIfExists(filePath As String) As String
    If Len(Dir(filePath)) > 0 Then
        GetFilePathIfExists = filePath
    End If
End Function

Sub TestGetFilePathIfExists()
    Dim filePath1 As String
    Dim filePath2 As String
    Dim pathToCheck As String
    Dim pathToTake As String

    ' Specify the file paths
    filePath1 = "firstPath\invalid" 
    filePath2 = "C:\Users\myusername\Desktop\TestFolder"

    If GetFilePathIfExists(filePath1) Then
         Debug.Print "Found in A"
         pathToTake = filePath1
         
    ElseIf GetFilePathIfExists(filePath2) Then
        Debug.Print "Found in B"
        pathToTake = filePath2
        
    Else
        ' If neither file path is found, use the path of the active workbook
        pathToTake = ThisWorkbook.Path
        Debug.Print "Found in C"
    End If
End Sub

现在,当执行此代码时,它将正确地识别路径是否存在并相应地设置 pathToTake 变量。如果路径 filePath2 存在,代码将打印 "Found in B",并正确地使用该路径。

常见问题解答

1. 为什么使用 Len(Dir(filePath)) 来检查路径是否存在?

Dir 函数返回指定路径的第一个文件的名称。如果路径不存在,则 Dir 返回空字符串,其长度为 0。因此,我们可以使用 Len(Dir(filePath)) 来检查路径是否存在。

2. 为什么修改后的函数不返回空字符串?

空字符串在 VBA 中被视为 False。如果函数返回空字符串,这将导致即使路径存在,函数也返回 False 的混乱结果。

3. 如果函数没有找到任何路径,pathToTake 变量会被如何设置?

如果函数没有找到任何路径,pathToTake 变量将被设置为活动工作簿的路径。

4. 有没有更好的方法来检查路径是否存在?

使用 GetFilePathIfExists 函数检查路径是否存在是一种简单而有效的方法。然而,还有一些其他方法,如使用 FileSystemObject 对象或 FileExists 函数。

5. 修改后的函数是否适用于所有版本的 Excel VBA?

修改后的函数适用于所有版本的 Excel VBA。