如何允许在Windows文件对话框中正常选择取消

时间:2017-02-17 22:54:14

标签: excel excel-vba exit vba

Hello All(专家和比我聪明的人),

我遇到了一个问题,当我点击取消Windows'文件打开'对话框时,它调试到这一行。我想要做的是,我想添加某种“异常”,如果我点击“取消”到“文件打开”对话框,它不会给我一个“运行时错误'1004':并且可以选择“结束”“调试”和“帮助”但相反,当用户点击取消时,它会正常退出。这是在VBA。这可能吗?我搜索周围并且无法找到有效的方法,因为这是一个独特的案例。我只是不希望'用户'必须被迫查看代码,如果他们改变了对文件'打开'的想法,而是让他们优雅地退出并仍然看着主他们最初的excel工作簿。

Workbooks.OpenText Filename:=strFileToOpen, StartRow:=11, DataType:=xlDelimited, Tab:=True, TrailingMinusNumber:=True

1 个答案:

答案 0 :(得分:0)

单击“取消”时,GetOpenFilename对话框将返回“FALSE”。试试这个:

Sub CancelFileOpenGracefully()
Dim strFileToOpen As String


    On Error GoTo GracefulExit:
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    strFileToOpen = Application.GetOpenFilename
    'Test if user didn't hit Cancel and run your code
    If strFileToOpen <> "FALSE" Then
        Workbooks.OpenText Filename:=strFileToOpen, StartRow:=11, DataType:=xlDelimited, _
        Tab:=True, TrailingMinusNumbers:=True
            'Do things
    End If
GracefulExit:
    Application.ScreenUpdating = True
    Application.EnableEvents = True
End Sub
相关问题