我创建了以下函数来查找文件并在找不到文件时给出错误:
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,也会发生这种情况。我做错了什么?
答案 0 :(得分:5)
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
进行迭代 - 请参阅this article。
For i = LBound(arrFileNames) To UBound(arrFileNames)