Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 836
Linga Avatar asked Oct 14 '25 03:10

Linga


1 Answers

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....
like image 188
CLR Avatar answered Oct 17 '25 06:10

CLR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!