DukeSilver
DukeSilver

Reputation: 748

Excel VBA Array() function causing type mismatch?

I've created the following function to look for files and give errors if the files aren't found:

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

When I go to call it, I get a type mismatch error though. This happens with a predefined array and also when trying to use the Array() function:

.
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)

This also happens if arrFileNames() is a Variant. What am I doing wrong?

Upvotes: 3

Views: 1559

Answers (1)

Mathieu Guindon
Mathieu Guindon

Reputation: 71167

Array doesn't return a typed array (e.g. String()).

Change your signature to take a Variant instead:

Public Function checkFileExistence(arrFileNames As Variant, Optional bShowErrMsg As Boolean = False) As Boolean

And you can always validate that you're looking at an actual array, with the IsArray function:

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

Also I'd warmly recommend changing your loop to a For...Next loop. Arrays don't want to be iterated with For Each - see this article.

For i = LBound(arrFileNames) To UBound(arrFileNames)

Upvotes: 6

Related Questions