Return 检查 UDF 中是否存在文件或目录时,空单元格为假

Return False on empty cells when checking if file or directory exists in UDF

给定样本 Excel 数据格式:

filepath test
C:\file.txt =PERSONAL.XLSB!checkExists(A2)
C:\dir\file.txt TRUE
C:\fake_dir FALSE
C:\fake_dir\file.txt FALSE
TRUE

我要运行下面的User-Defined公式,叫做checkExists;这使用 DIR 检查给定单元格中的值以查看该目录或文件是否存在,并且 returns 一个布尔值。

Public Function checkExists(path As String) As Boolean

'   Check if string is empty
    If (IsEmpty(path) = False) Then

'       Check if file/dir exists
        If ((Dir(path, vbNormal + vbDirectory)) <> vbNullString = False) Then
'           String is not empty, and file/dir exists; return True
            checkExists = True

        Else
'           File does not exist; return False
            checkExists = False
        
        End If
    
    Else
'       String is empty; return False
        checkExists = False
    
    End If

End Function

我正在努力让它识别给定的单元格是空白的——比如这里的 A6。这里的公式写成returnsTRUE,需要的时候FALSE.

我意识到我正在向它传递一个 String,而且我可能需要传递另一种 object 类型,例如 Range 或 Variant...但我不能弄清楚如何让这些 object 类型与我的代码一起工作。我也不知道同时使用 vbNormal(文件)和 vbDirectory(目录)是否会导致问题。我查找过 ActiveCell{Range}.Address 等调用,但我卡住了。

如有任何帮助,我们将不胜感激。谢谢。

使用 Dir

检查文件或文件夹是否存在

使用Len

Public Function checkExists(fPath As String) As Boolean

'   Check if the length of the string is greater than 0
    If Len(fPath) > 0 Then

'       Check if the length of 'Dir' is greater than 0
        If Len(Dir(fPath, vbNormal + vbDirectory)) > 0 Then

'           File/dir exists; return True
            checkExists = True

        Else
'           File does not exist; checkExists is False by default
            'checkExists = False
        
        End If
    
    Else
'       The length of the string is 0; checkExists is False by default
        'checkExists = False
    
    End If

End Function

使用Len

Public Function checkExistsLen(fPath As String) As Boolean
    If Len(fPath) > 0 Then
        If Len(Dir(fPath, vbNormal + vbDirectory)) > 0 Then
            checkExists = True
        End If
    End If
End Function

使用vbNullString""

Public Function checkExists(fPath As String) As Boolean
    If fPath <> "" Then
        If Dir(fPath, vbNormal + vbDirectory) <> "" Then
            checkExists = True
        End If
    End If
End Function