3
votes

I'm working on a code that uses the Application.GetOpenFileName. Im trying to ensure that that code doesn't break if someone hits cancel when selecting a file. I have a if statement that states if file = "false" then show a msgbox and exit sub. This works fine when no file is selected, however when I run the macro with the files selected then I get a Type Mismatch error. Ive tried a bunch of different runarounds and nothing has worked. Ive looked at other similar questions on here but nothing has worked for me.

Dim nom As String
Dim wb1, wb2, wb3, wb4, wb5 As Excel.Workbook
Dim i, j, k, file As Variant

nom = ActiveWorkbook.Name
If CurDir() <> CurDir("J:") Then
    ChDrive "J:"
    ChDir "J:FEA Material Data"
End If
For i = 1 To 5
Application.ScreenUpdating = False
MsgBox ("Select Compound" & vbNewLine & vbNewLine & "If Data From Criterion, Select Loading Only" & vbNewLine & vbNewLine & "If Data From Alliance, Select All")
file = Application.GetOpenFilename( _
            FileFilter:="Text Files (*.csv), *.csv", _
            MultiSelect:=True)
    If file = "False" Then
        MsgBox "No File Selected"
        Exit Sub
    Else
    counter = 1
        While counter <= UBound(file)
            Workbooks.Open file(counter)
            counter = counter + 1
        Wend
    End If 
more code
1
if not isarray(file) then if file = "false" exit sub??? - Dirk Reichel

1 Answers

3
votes

When it has files it returns a variant with an array. Debug.Print VarType(file) returns 8204. So you need to check the array for file names. If the user selects Cancel then the Variant will be a boolean.

If VarType(file) = 11 Then
    MsgBox "No File Selected"
    Exit Sub

Or more readable (thanks to Dirk Reichel):

If Not IsArray(file) Then
    MsgBox "No File Selected"
    Exit Sub

Determining the Type of a Variant