Search code examples
excelvbaimport-from-excelgetopenfilename

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


I'm importing a specific sheet in a workbook into the current workbook that I'm working with. Import works fine consecutively by deleting the current sheet before importing again. There is one small thing that needs to be fixed. When I cancel or exit the GetOpenFilename application, it comes with:

False.xlsx was not found (...)

so I added:

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

in the Sub import_click(), but I don't want it to ask me for the file twice. However, if I don't include filespec = Application.GetOpenFilename() it doesn't work. Here's the code:

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

How do I successfully exit or cancel the GetOpenFilename application and only ask for the file once?


Solution

  • variable filespec has to be public, if you want to use it in another sub's. Add this line before "Sub import_click()" : Public filespec As Variant and delete/comment line filespec = Application.GetOpenFilename() in Sub import