Forum Discussion

Contrail1234's avatar
Contrail1234
Copper Contributor
Jul 12, 2026

Runt-time Error 1401 When Importing a CSV file Using VBA

I am beyond frustrated that I cannot make this work. Let me explain.

My spreadsheet needs to import a standard CSV file then parse that information into several different worksheets. The very first time I ran the import code it worked. The second time and every time after that it fails with the "Run-time error '1004': Application-defined or object-defined error" message. I tried this on a different computer with the same results first run it worked, every run after that it fails.

Here is the code:

Sub ImportCSV()
    Dim ws As Worksheet
    Dim csvFilePath As String
    Dim lastRow As Long

    ' Set the worksheet where you want to load the data
    Set ws = ActiveWorkbook.Sheets("Raw")

    ' Specify the path to your CSV file
    csvFilePath = "exportusers-all.csv"

    ' Clear existing data in the worksheet
    ws.Cells.Clear

    ' Import the CSV file
    With ws.QueryTables.Add(Connection:="TEXT;" & csvFilePath, Destination:=ws.Range("A1"))
        .TextFileParseType = xlDelimited
        .TextFileCommaDelimiter = True
        .Refresh
    End With
End Sub

This is the code I've found in numerous places when I search the internet when I search how to do it. I have tried this as a normal user and "Run as Administrator" both fail.

My Trust Center > Macro Settings are as follows:

  • Enable VBA macros - Selected
  • Trust access to the VBA project object model - Checked

The CSV file can be opened in a text editor and Excel without any issues, but if I try to import it, it fails completely. Any help or suggestions to resolve this problem would be greatly appreciated. Thanks.

 

No RepliesBe the first to reply