Search code examples
vbaexcelexcel-2010excel-2007

Run time error 1004 excel cannot find the text file to refresh this external range


I'm trying to convert tsv files in a folder to xlsx format by importing them as text file using Data=>From Text option via VBA.

During that encountered this error

enter image description here

enter image description here

Code:

Sub convert()

Dim CSVfolder As String, XlsFolder As String, fname As String, wBook As Workbook

CSVfolder = ActiveSheet.Range("B2").Value & "\"

fname = Dir(CSVfolder & "*.tsv")

Do While fname <> ""
    Workbooks.Add
    
    Set wBook = ActiveWorkbook
    
       With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fname, Destination:=Range("$A$1"))
        .Name = fname
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 65001
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierNone
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
   
    wBook.Close False
    fname = Dir
    
 Loop
End Sub

End Sub


Why i'm getting the error in .Refresh BackgroundQuery:=False ?


Solution

  • The error is happening there as it's at the Refresh stage that it looks for the file.

    The issue is that Fname won't contain the path.

    Change your connection to:

    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & CSVfolder & fname, Destination....