Filedialog错误:类型不匹配

时间:2017-04-11 01:57:53

标签: excel vba

当我没有添加If-Else函数时,我的程序工作...... If部分工作,它执行消息框。但是,else部分没有工作......不知道为什么......错误是类型不匹配,它可能从这一行开始:设置wb2 = Workbooks.Open(FileToOpen) 在此先感谢您的帮助:)

Dim FileToOpen As String
Dim wb2 As Workbook
Dim sheet As Worksheet
FileToOpen = Application.GetOpenFilename _
              (Title:="Please choose a Excel File to Open", _
               FileFilter:="Excel Files *.xlsx(*.xlsx),")
If FileToOpen = False Then
    MsgBox "No file selected", vbExclamation, "Sorry!"
    Exit Sub
Else
    Set wb2 = Workbooks.Open(FileToOpen)
    Set sheet = wb2.Worksheets(1)
    sheet.UsedRange.Copy Destination:=ThisWorkbook.Worksheets(2).range("A1")
    Sheet1.range("B30").Value = FileToOpen
    Workbooks(2).Close
End If

1 个答案:

答案 0 :(得分:1)

第一个分支中有Exit Sub,因此Else是多余的 - 您可以将缩进级别减少一个。

问题在于If FileToOpen = FalseStringBoolean字面值进行比较,而VBA(理所当然地)不知道该如何评估: em>是什么导致类型不匹配错误。

GetOpenFileName返回Variant String然后您选择文件,或者取消对话框时Boolean - 因此,验证类型而不是值:

Dim path As Variant
path = Application.GetOpenFilename(Title:="Please choose a Excel File to Open", 
                                   FileFilter:="Excel Files *.xlsx(*.xlsx),")

'path is Variant/Boolean if cancelled, Variant/String if valid.
If VarType(path) = vbBoolean Then
    MsgBox "No file selected", vbExclamation, "Sorry!"
    Exit Sub
End If

Debug.Assert VarType(path) = vbString
With Application.Workbooks.Open(path)
    .Worksheets(1).UsedRange.Copy ThisWorkbook.Worksheets(2).range("A1")
    Sheet1.range("B30").Value = path
    .Close
End With