簡體   English   中英

檢查 UDF 中是否存在文件或目錄時,在空單元格上返回 False

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

給定樣本 Excel 數據的格式:

文件路徑 測試
C:\file.txt =PERSONAL.XLSB!checkExists(A2)
C:\dir\file.txt 真的
C:\fake_dir 錯誤的
C:\fake_dir\file.txt 錯誤的
真的
  • A1 和 A2 是標題
  • A2 和 A3 中的值是存在的文件路徑
  • A4是一個不存在的目錄
  • A5是一個不能存在的文件,因為它的目錄不存在
  • A6 為空白
  • B2 只是顯示我如何調用公式(它保存在我的 PERSONAL.XLSB 項目容器中)

我想運行以下名為checkExists的用戶定義公式; 這使用DIR檢查給定單元格中的值以查看該目錄或文件是否存在,並返回 boolean。

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。 當我需要FALSE時,所寫的公式在這里返回TRUE

我意識到我正在傳遞一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM