我对VBA很新。只要单击对话框中的取消/退出按钮,我就会一直收到类型不匹配的错误。该错误出现在Application.GetOpenFileName行上。有人知道这里有什么问题吗?我尝试了几种方法但没有一种方法可以工作:(
谢谢!
这是我的代码:
Private Sub cmdBrowse_Click()
Application.ScreenUpdating = False
Dim i As Long, j As Long, iCheck As Long
Dim fname() As Variant
Dim wkbNameList As String, wkbNamePath As String
Dim win As Window
fname = Application.GetOpenFilename(filefilter:="Excel, *xlsx; *xlsm", MultiSelect:=True)
If fname = "False" Then
Exit Sub
End If
For i = LBound(fname) To UBound(fname)
workbooks.Open Filename:=fname(i)
wkbNameList = wkbNameList & workbooks(i + 1).Name & vbCrLf
wkbNamePath = wkbNamePath & fname(i) & " , "
Next i
答案 0 :(得分:0)
正如Kostas K.在对h2so4的答复的评论中所指出的那样,该方法在取消对话框时返回布尔值(False),并在选择文件时返回数组。
我建议尝试对h2so4的代码进行以下修改:
Private Sub cmdBrowse_Click()
Application.ScreenUpdating = False
Dim i As Long, j As Long, iCheck As Long
Dim fname() As Variant
Dim wkbNameList As String, wkbNamePath As String
Dim win As Window
fname = Application.GetOpenFilename(filefilter:="Excel, *xlsx; *xlsm", MultiSelect:=True)
'the only option to get boolean is to have cancelled the dialog, which gives False for the variable
If VarType(fname) = vbBoolean Then
Exit Sub
Else
For i = LBound(fname) To UBound(fname)
workbooks.Open Filename:=fname(i)
wkbNameList = wkbNameList & workbooks(i + 1).Name & vbCrLf
wkbNamePath = wkbNamePath & fname(i) & " , "
Next i
End If
End Sub