Import CSV data onto a sheet - Very good.

Post Reply
wwj
Posts: 2497
Joined: 27 Jan 2007 08:16

Import CSV data onto a sheet - Very good.

Post by wwj »

From OpenChat.

To achieve this task in VBA, you can use the following steps:
  • Open the CSV file.
    Copy columns A through K from the CSV file.
    Paste these columns into another sheet.

Code: Select all

Sub CopyCsvData()
    Dim csvPath As String
    Dim wbCsv As Workbook
    Dim wsCsv As Worksheet
    Dim wsDest As Worksheet
    Dim lastRow As Long
    
    ' Specify the path to your CSV file
    csvPath = "C:\path\to\your\file.csv"
    
    ' Open the CSV file
    Set wbCsv = Workbooks.Open(csvPath)
    Set wsCsv = wbCsv.Sheets(1)
    
    ' Specify the destination worksheet (this assumes the destination is in the same workbook as this VBA code)
    Set wsDest = ThisWorkbook.Sheets("Sheet1") ' Change "Sheet1" to your destination sheet name
    
    ' Find the last row in the CSV to determine the range to copy
    lastRow = wsCsv.Cells(wsCsv.Rows.Count, "A").End(xlUp).Row
    
    ' Copy columns A through K from the CSV file
    wsCsv.Range("A1:K" & lastRow).Copy
    
    ' Paste into the destination worksheet starting at cell A1
    wsDest.Range("A1").PasteSpecial Paste:=xlPasteValues

    ' Optional: Clear the clipboard to free up memory
    Application.CutCopyMode = False
    
    ' Close the CSV file
    wbCsv.Close SaveChanges:=False
    
    ' Deselect the copied range by selecting cell L1 on the destination sheet
    wsDest.Range("L1").Select

    MsgBox "Data copied successfully!"
    
End Sub


Post Reply