与WorkBooks.OpenText命令相关的错误处理

时间:2017-04-20 15:37:52

标签: excel vba

我正在使用标准的Workbooks.OpenText函数但是当我点击取消时,它会调试到我的代码中,这是我不想要的。相反,我想要一个错误处理程序,所以如果我点击取消,会出现一个错误框,说明"没有选择文件"。我无法弄清楚如何放入一个钩子来识别这个OpenText被取消了。

 Set myfile = Application.FileDialog(msoFileDialogFolderPicker)
 Workbooks.OpenText Filename:=myfile, DataType:=xlDelimited, 
 Origin:=xlWindows, Other:=True, OtherChar:=","

1 个答案:

答案 0 :(得分:0)

你可以这样做:

Sub MySub()
    Dim fd As FileDialog
    Dim vrtSelectedItem As Variant

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd
        ' TODO configure file dialog
        ' .AllowMultiSelect = ???
        ' .Filters = ???
        ' ...

        If .Show = -1 Then
            ' TODO code to handle FileDialog OK button
            ' Depending on settings user may be able to select multiple items
            For Each vrtSelectedItem in .SelectedItems
                Debug.Print vrtSelectedItem 
                ' Workbooks.OpenText Filename:=vrtSelectedItem, ...
            Next vrtSelectedItem 
        Else
            ' TODO code to handle FileDialog Cancel button
            Debug.Print "user hit cancel"
        End If
    End With

    Set fd = Nothing
End Sub

希望有所帮助