Excel VBA Array()函数导致类型不匹配?

Duk*_*ver 3 arrays excel vba excel-vba

我创建了以下函数来查找文件并在找不到文件时给出错误:

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
Run Code Online (Sandbox Code Playgroud)

当我去调用它时,我得到了类型不匹配错误.使用预定义的数组以及尝试使用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)
Run Code Online (Sandbox Code Playgroud)

如果arrFileNames()是Variant,也会发生这种情况.我究竟做错了什么?

Mat*_*don 5

Array不返回类型数组(例如String()).

更改您的签名Variant取代:

Public Function checkFileExistence(arrFileNames As Variant, Optional bShowErrMsg As Boolean = False) As Boolean
Run Code Online (Sandbox Code Playgroud)

您可以随时使用以下IsArray函数验证您正在查看实际数组:

    If Not IsArray(arrFileNames) Then Err.Raise 5, "CheckFileExistence", "Expected array, but received a " & TypeName(arrFileNames) & "."
Run Code Online (Sandbox Code Playgroud)

另外,我强烈建议将循环更改为For...Next循环.数组不希望被迭代For Each- 请参阅此文章.

For i = LBound(arrFileNames) To UBound(arrFileNames)
Run Code Online (Sandbox Code Playgroud)

  • @dwirony我还没有找到正确的措辞,但基本上......数组在VBA中传递的方式有点笨重;-)`Variant()`说"每个项目都是`Variant`" (并且VBA不会为它采用`Integer()`或`String()`,而`Variant`表示"这可以是包括任何数组的任何东西". (2认同)