我创建了以下函数来查找文件并在未找到文件时给出错误:
Public Function checkFileExistence(arrFileNames() As String, Optional bShowErrMsg As Boolean = False) As Boolean
' This function looks for every file name in arrFileNames and returns True if all exist else False
' Optional: bShowErrMsg = True will tell the user which file was missing with a MsgBox
Dim file As Variant
For Each file In arrFileNames
If Len(Dir(file, vbNormal)) = 0 Then
checkFileExistence = False
If bShowErrMsg = True Then MsgBox (file & " was not found.")
Exit Function
End If
Next file
checkFileExistence = True
End Function
当我去调用它时,我收到类型不匹配错误。预定义数组以及尝试使用 Array() 函数时都会发生这种情况:
.
Dim filesToFind(1 To 3) As String
filesToFind(1) = "image.png"
filesToFind(2) = "test.png"
filesToFind(3) = "test.fred"
Debug.Print checkFileExistence(filesToFind, True)
Debug.Print checkFileExistence(Array("image.png", "test.png", "test.fred"), True)
如果 arrFileNames() 是 Variant,也会发生这种情况。我究竟做错了什么?
Array
不返回类型化数组(例如String()
).
更改您的签名以获取Variant
反而:
Public Function checkFileExistence(arrFileNames As Variant, Optional bShowErrMsg As Boolean = False) As Boolean
并且您始终可以使用以下命令来验证您正在查看的是否是一个实际数组IsArray
功能:
If Not IsArray(arrFileNames) Then Err.Raise 5, "CheckFileExistence", "Expected array, but received a " & TypeName(arrFileNames) & "."
另外我强烈建议将您的循环更改为For...Next
环形。数组不想被迭代For Each
- see 本文 http://analystcave.com/vba-for-loop-vs-for-each-loop/.
For i = LBound(arrFileNames) To UBound(arrFileNames)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)