[英]Return False on empty cells when checking if file or directory exists in UDF
Given sample Excel data in the format:给定样本 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![]() |
I want to run the following User-Defined Formula, called checkExists
;我想运行以下名为
checkExists
的用户定义公式; this uses DIR
to check the value in a given cell to see if that directory or file exists, and returns a boolean.这使用
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
I'm struggling with getting it to recognise that a given cell is blank -- such as A6 here.我正在努力让它识别给定的单元格是空白的——比如这里的 A6。 The formula as written returns
TRUE
here, when I need FALSE
.当我需要
FALSE
时,所写的公式在这里返回TRUE
。
I realise I'm passing it a String
, and there is probably another object type I need to pass it, such as a Range or Variant... but I can't work out how to get those object types to work with my code.我意识到我正在传递一个
String
,并且可能还有另一个 object 类型我需要传递它,例如 Range 或 Variant ......但我不知道如何让那些 object 类型与我的代码一起使用. I also don't know if using both vbNormal
(files) and vbDirectory
(directories) is causing an issue.我也不知道同时使用
vbNormal
(文件)和vbDirectory
(目录)是否会导致问题。 I've looked up calling things like ActiveCell
, {Range}.Address
, and so on, but I'm stuck.我查找过调用诸如
ActiveCell
、 {Range}.Address
等的东西,但我被困住了。
Any help would be much appreciated.任何帮助将非常感激。 Thank you.
谢谢你。
Dir
Dir
检查文件或文件夹是否存在Using Len
使用
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
Using Len
使用
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
Using vbNullString
or ""
使用
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.