VBA function to copy data from CSV to Excel workbook.


'------------------------------------------------------------------------- 
' Source: risksir.com 
' Description: Copy data from CSV to Excel workbook 
'------------------------------------------------------------------------- 
Sub CopyCSVtoWorkbook()
    Dim wbTarget As Workbook, wbSource As Workbook
    Dim wsTarget As Worksheet, wsSource As Worksheet
    Dim csvPath As String
    
    ' Set the path of the CSV file
    csvPath = "C:\path\to\your\file.csv" ' Change to your CSV file path

    ' Reference the target workbook and worksheet
    Set wbTarget = ThisWorkbook
    Set wsTarget = wbTarget.Sheets("Sheet1")

    ' Clear columns A:D in the target worksheet
    wsTarget.Range("A:D").ClearContents

    ' Open the CSV file
    Set wbSource = Workbooks.Open(csvPath)
    Set wsSource = wbSource.Sheets(1) ' Assuming the data is in the first sheet

    ' Copy data from the CSV file and paste it into the target worksheet
    wsSource.UsedRange.Copy Destination:=wsTarget.Range("A1")

    ' Close the source workbook without saving
    wbSource.Close False
End Sub