在 "Application.GetOpenFilename" 中单击退出或取消时出现错误消息

Error message when clicking Exit or Cancel in "Application.GetOpenFilename"

我正在将工作簿中的特定 sheet 导入到我正在使用的当前工作簿中。通过在再次导入之前删除当前 sheet,导入可以连续正常工作。有一件小事需要修复。当我取消或退出 GetOpenFilename 应用程序时,它附带:

False.xlsx was not found (...)

所以我补充说:

filespec = Application.GetOpenFilename() 
If filespec = False Then Exit Sub

Sub import_click() 中,但我不希望它向我索要文件两次。但是,如果我不包括 filespec = Application.GetOpenFilename() 它不起作用。这是代码:

Sub import_click()
    filespec = Application.GetOpenFilename()

    If filespec = False Then Exit Sub

    Call deletedatasheet
    Call import

    MsgBox "Data imported", vbInformation

End Sub

Private Sub import()

Dim wsMaster As Worksheet
Dim rd As Range

Application.ScreenUpdating = False
Application.DisplayAlerts = False

    If wsMaster Is Nothing Then
        ThisWorkbook.Sheets.Add
        Set wsMaster = ActiveSheet
        Set rd = wsMaster.Range("A1")
        wsMaster.Name = "Reviewed"
        filespec = Application.GetOpenFilename()
        Set wb = Workbooks.Open(Filename:=filespec)
        Sheets("Reviewed").Activate
        Cells.Copy rd
        wb.Close
    End If

Application.ScreenUpdating = True
Application.DisplayAlerts = True


End Sub

Sub deletedatasheet()
    Dim ws As Worksheet

    Application.DisplayAlerts = False
    For Each ws In ThisWorkbook.Sheets
        If ws.Name = "Reviewed" Then
            ws.Delete
        End If
    Next
    Application.DisplayAlerts = True
End Sub

如何成功退出或取消GetOpenFilename应用程序并且只请求一次文件?

变量文件规范必须是 public,如果你想在另一个 sub 中使用它。 在 "Sub import_click()" 之前添加此行:Public filespec As Variant 和子导入

中的delete/comment行filespec = Application.GetOpenFilename()