我正在编写使用 Application.GetOpenFileName 的代码。我试图确保如果有人在选择文件时点击取消,该代码不会中断。我有一个 if 语句,说明 if file = "false"然后显示一个 msgbox 并退出 sub。当没有选择文件时,这工作正常,但是当我运行带有选定文件的宏时,我得到一个类型不匹配错误。我尝试了很多不同的解决方法,但没有任何效果。我在这里查看了其他类似的问题,但对我没有任何帮助。
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
最佳答案
当它有文件时,它返回一个带有数组的变体。 Debug.Print VarType(file)
返回 8204。因此您需要检查数组中的文件名。如果用户选择 Cancel,则 Variant 将为 bool 值。
If VarType(file) = 11 Then
MsgBox "No File Selected"
Exit Sub
或更具可读性(感谢 Dirk Reichel):
If Not IsArray(file) Then
MsgBox "No File Selected"
Exit Sub
关于vba - 如果文件 = "False"Application.GetOpenFileName 错误 13 类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35726641/