Error canceling file import in Excel

2

I'm building a Macro to import a file into Excel. At some point, when the file's location is requested, if the Worksheet user cancels the import option, the following error message is returned:

  

Excel can not find the text file to refresh this external data range

After this the execution of the macro is terminated. Checking Debug . the error occurs in the .Refresh BackgroundQuery:=False parameter of the procedure.

Below the import code:

Public Sub btnImportarTXT_Click()

    ' Sub para importar arquivo .TXT

    Dim Dir As String

    dirArquivo = Application.GetOpenFilename(FileFilter:="Text File, *.txt")

    With Sheets("Extract").QueryTables.Add(Connection:="TEXT;" & dirArquivo, Destination:=Range("Extract!$A$1"))
        .Name = "extract"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 1252
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

    ' Worksheets("Extract").Protect UserInterfaceOnly:=True

    MsgBox "Arquivo importado!", vbOKOnly, "Sucesso!"

End Sub
    
asked by anonymous 13.01.2015 / 17:26

2 answers

1

Your comment explains that "cancel" is the user canceling the dialog box that asks for a file to be selected.

In this case where the user decided not to import the file, you should "skip" the code that imports.

The Application.GetOpenFilename method returns the file name if it is selected and returns Fase if the user clicked "cancel" in the dialog box (it is, I know, weird).

Then you can test the return of GetOpenFilename and only execute the import code if the return is other than False . More or less like this:

dirArquivo = Application.GetOpenFilename(FileFilter:="Text File, *.txt")

if dirArquivo <> False then
    'código para importar aqui.
end if
    
13.01.2015 / 17:58
2

The Application.GetOpenFilename method returns a value of type Variant , which can be a file, an array of files or the boolean value false if the operation is canceled, then you can do a check before starting the import, something like this:

Public Sub btnImportarTXT_Click()

    ' Sub para importar arquivo .TXT

    Dim Dir As String

    dirArquivo = Application.GetOpenFilename(FileFilter:="Text File, *.txt")

    If dirArquivo <> False Then ' verifica se o usuário cancelou a importação
        With Sheets("Extract").QueryTables.Add(Connection:="TEXT;" & dirArquivo, _
        Destination:=Range("Extract!$A$1"))
            .Name = "extract"
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 1252
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With

        ' Worksheets("Extract").Protect UserInterfaceOnly:=True

        MsgBox "Arquivo importado!", vbOKOnly, "Sucesso!"
    Else
        MsgBox "Importação cancelada!", vbOKOnly, "Aviso!"
    End If

End Sub
    
13.01.2015 / 17:58