[英]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 | 錯誤的 |
真的 |
我想運行以下名為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.