user1898958
user1898958

Reputation: 93

Reading CSV file into excel using VBA then outputting the results to a specific worksheet

I've been searching for a while and can't find a simple solution. I've got a csv file that I would like to read into excel using vba and output the results into a specific cell range on a specific worksheet.

I've been using the following code, but if I run the excel macro twice it basically appends the data on the next blank column instead of copying over it. It also only pastes it into the active sheet instead of my specific sheet.

Any suggestions on how I can do this?

Thanks,

Public Sub Example()
    Const csPath As String = "starting_positions.csv"
    Dim ws As Excel.Worksheet
    Set ws = Excel.ActiveSheet
    With ws.QueryTables.Add("TEXT;" & csPath, ws.Cells(1, 1))
        .FieldNames = True
        .AdjustColumnWidth = True
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileCommaDelimiter = True
        ''// This array will need as many entries as there will be columns:
        .TextFileColumnDataTypes = Array(xlTextFormat, xlTextFormat)
        .Refresh
    End With
End Sub

Upvotes: 3

Views: 18593

Answers (1)

Peter L.
Peter L.

Reputation: 7304

Assuming you run the code in the same workbook you need to collect CSV data to, try the following:

  1. Replace Set ws = Excel.ActiveSheet with Set ws = ThisWorkbook.Sheets(1) or Set ws = ThisWorkbook.Sheets("Sheet1") to define any specific sheet using either its index or name.
  2. ws.UsedRange.ClearContents place prior With... block will clear the whole sheet, and therefore new data will be placed to the same place as before.

One more hint: in case you're going to use this macro many times - do not create every time a new connection. In case all the options are similar - only use .Refresh method.

If you're stuck with the merging of code parts - try to use macro recorder passing any of the steps manually. For your case this will solve the majority of troubles. Good luck!

Upvotes: 4

Related Questions