VBA to Import .csv to Excel

ionelz

Board Regular
Joined
Jan 14, 2018
Messages
248
Office Version
  1. 365
Platform
  1. Windows
Hi,
Please Help with a VBA Code, not sure how complicate could be.
I want o Import an .csv file ( want to be able to browse for .csv file) to my excel file, in Sheet2 starting cell B2
The .csv file data is delimited by semicolon ;
Thanks all
 
01. The 100 there is the column count for the array. It could be increased in the rare cases that needed it to be larger.

02. Certainly you can do that if you want to.
Just change:
VBA Code:
            CSV_FileRowColumnsArray = Split(All_CSV_RowsFromCSV_FileArray(CSV_FileRow), ";")            '       Load contents of row to CSV_FileRowColumnsArray

to:
VBA Code:
            CSV_FileRowColumnsArray = Split(All_CSV_RowsFromCSV_FileArray(CSV_FileRow), Range("A1"))    '       Load contents of row to CSV_FileRowColumnsArray
 
Upvote 0

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.
Sheet1 Range("A1") ?
Just want to say that Range(" A1") is from Sheet1
 
Upvote 0
It is not needed in your case because the cell A1 is on the same sheet as the button.

If it makes you sleep better, yes, you can add the sheet.

Sheet1.Range("A1") or Sheets("Sheet1").Range("A1")
 
Upvote 0
Thank you !
wsDestination.UsedRange.Clear

Could this be replaced with a "simple" clear
Looks like I loose conditional formating with the one above
 
Upvote 0
Try the following:

Change:
VBA Code:
    wsDestination.UsedRange.Clear                                                                       ' Clear the destination sheet

to:
VBA Code:
    wsDestination.UsedRange.Value = ""
 
Upvote 0
Can this be changed to import data from other excel formats and not just csv files? Thank you for any help you can provide.
 
Upvote 0
The Code modules I provided does all the dirty work for you. :)

Let me give a step by step on how to use them.

1) Start with a new excel workbook.
2) Press Alt+F11 to open the VB Editor
3) Press Alt+I and then select 'Module' from the window that pops up
4) In the big window that pops up paste the following code:

VBA Code:
Sub CreateAClickableMacroButton()
'
    Dim ButtonHeighth                       As Long, ButtonLength                           As Long
    Dim ButtonTitle                         As String
    Dim CellToPutButtonInto                 As String
    Dim CodeNameOfSheetToPutClickableButton As String
    Dim LeftAddress                         As String, TopAddress                           As String
    Dim MacroToRunWhenButtonIsClicked       As String
    Dim NameOfSheetToPutClickableButton     As String, NameOfMacroToRunWhenButtonIsClicked  As String
'
    CellToPutButtonInto = "B2"                                              ' <--- Set this to the cell that you want the clickable button to be put into
    ButtonTitle = "Import CSV File"                                         ' <--- Set this to what you want displayed on the button
    NameOfSheetToPutClickableButton = "Sheet1"                              ' <--- Set this sheet name to the desired sheet to put the clickable button into
    NameOfMacroToRunWhenButtonIsClicked = "LoadCSV_FileToSheet"             ' <--- Set this to the name of the subroutine that you want to run when button is clicked
'
    CodeNameOfSheetToPutClickableButton = Sheets(NameOfSheetToPutClickableButton).CodeName  ' Find the CodeName of the SheetName
    MacroToRunWhenButtonIsClicked = CodeNameOfSheetToPutClickableButton & "." & NameOfMacroToRunWhenButtonIsClicked
'
    ButtonHeighth = 15                                                      ' <--- Set this to the Default Height of button
    ButtonLength = Round(Len(ButtonTitle) * 5 * 0.98)                       ' Calculated value to set the ButtonLength to
'
    With Sheets(NameOfSheetToPutClickableButton)
        With .Buttons.Add(1, 1, ButtonLength, ButtonHeighth)
            .Top = .Parent.Range(CellToPutButtonInto).Top
            .Left = .Parent.Range(CellToPutButtonInto).Left
            .Caption = ButtonTitle                                          ' Title of clickable button
            .OnAction = MacroToRunWhenButtonIsClicked                       ' Subroutine to run when button is clicked
        End With
    End With
End Sub

5) Make any adjustments that you want to make to that code
6) Press Alt+F4 to return to Excel sheet
7) Right click the sheet tab at the bottom of the excel sheet that you elected to place the Button into.
8) select the 'View Code' from the window that pops up.
9) In the big window that pops up, paste the following code:

VBA Code:
Sub LoadCSV_FileToSheet()
'
    Application.ScreenUpdating = False                                                          ' Turn ScreenUpdating off
'
    Dim startTime       As Single
    Dim CSV_FileToOpen  As Variant
'
    CSV_FileToOpen = Application.GetOpenFilename("Text files,*.csv", , "Select file", , False)  ' Save full path of CSV file to CSV_FileToOpen
    If CSV_FileToOpen = False Then                                                              ' Exit Sub if user cancelled
        MsgBox "No file selected - exiting"
        Exit Sub
    End If
'
    startTime = Timer                                                                           ' Start the stopwatch
'
    Application.ScreenUpdating = False                                                          ' Turn ScreenUpdating off
'
    Dim CSV_ColumnMinus1                As Long, CSV_FileRow                As Long
    Dim FreeFileNumber                  As Long
    Dim RowNumber                       As Long
    Dim All_CSV_RowsFromCSV_FileArray   As Variant, CSV_FileRowColumnsArray As Variant
    Dim Partitioned_CSV_FileArray       As Variant
    Dim wsDestination                   As Worksheet
'
    Set wsDestination = Sheets("Sheet2")                                                ' <--- Set this to the sheet name to dump Partitioned_CSV_FileArray
'
    FreeFileNumber = FreeFile                                                                   ' Get an unused file number
    Open CSV_FileToOpen For Input As #FreeFileNumber
'
    If Err.Number <> 0 Then                                                                     ' If error occurred then ...
        MsgBox "File open error #" & Err.Number & "!", vbCritical, "Error!"                     '   Display error #
        Exit Sub                                                                                '   Exit sub
    End If
'
    All_CSV_RowsFromCSV_FileArray = Split(Input(LOF(FreeFileNumber), #FreeFileNumber), vbCrLf)  ' Load all Rows in file to All_CSV_RowsFromCSV_FileArray
    Close #FreeFileNumber
'
    RowNumber = 0                                                                               ' Initialize RowNumber
'
    ReDim Partitioned_CSV_FileArray(1 To UBound(All_CSV_RowsFromCSV_FileArray), 1 To 100)               ' Set rows/columns for Partitioned_CSV_FileArray
'
    For CSV_FileRow = LBound(All_CSV_RowsFromCSV_FileArray) To UBound(All_CSV_RowsFromCSV_FileArray)    ' Loop through all rows of CSV file
        If All_CSV_RowsFromCSV_FileArray(CSV_FileRow) <> vbNullString Then                              '   If CSV row is not blank then ...
            CSV_FileRowColumnsArray = Split(All_CSV_RowsFromCSV_FileArray(CSV_FileRow), ";")            '       Load contents of row to CSV_FileRowColumnsArray
'
            RowNumber = RowNumber + 1                                                                   '       Increment RowNumber
'
            For CSV_ColumnMinus1 = LBound(CSV_FileRowColumnsArray) To UBound(CSV_FileRowColumnsArray)   '       Loop through columns
                Partitioned_CSV_FileArray(RowNumber, CSV_ColumnMinus1 + 1) = _
                        CSV_FileRowColumnsArray(CSV_ColumnMinus1)                                       '           Add values to Partitioned_CSV_FileArray
            Next                                                                                        '       Loop back
        End If
    Next                                                                                                ' Loop back
'
    wsDestination.UsedRange.Clear                                                                       ' Clear the destination sheet
    wsDestination.Range("B2").Resize(UBound(Partitioned_CSV_FileArray, 1), UBound(Partitioned_CSV_FileArray, 2)).Value = Partitioned_CSV_FileArray       ' Display Partitioned_CSV_FileArray to sheet
    wsDestination.UsedRange.EntireColumn.AutoFit                                                        ' Autofit used columns
'
    Application.ScreenUpdating = True                                                                   ' Turn ScreenUpdating back on
'
    Debug.Print RowNumber & " Rows of data processed from the CSV file."    ' Display the # of data lines that were processed to the 'Immediate Window'(CTRL-G)
    Debug.Print "Time to complete = " & Timer - startTime & " seconds."                                 ' about .1 seconds
End Sub

10) Press Alt+F4 to return to Excel sheet
11) Press Alt+F8 and double click the 'CreateAClickableMacroButton' ' This will create the button on the sheet that you chose
12) Press F12 to 'Save As' & save the file as a 'xlsm' file
13) Close out the file and reopen it.
14) From then on you can click the button that was created and it will execute the code to ask for the CSV file location, etc.
Hi @johnnyL

Many thanks for posting this fantastic LoadCSV_FileToSheet() script, it works like a dream. For my usage, I'm trying to work out how to amend the script, so any imported files are appended to the end of any existing data, but I've not been able to work it out as yet.

I've stopped my worksheet from being cleared and also remove any duplicate data at the end of the script.

I've added the following lines to work out the last line of date + 1.

DataLRow = (ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row) + 1
DataLRowA = "A" & DataLRow

And changed

wsDestination.Range("B2").Resize(UBound(Partitioned_CSV_FileArray, 1), UBound(Partitioned_CSV_FileArray, 2)).Value = Partitioned_CSV_FileArray

to

wsDestination.Range(DataLRowA).Resize(UBound(Partitioned_CSV_FileArray, 1), UBound(Partitioned_CSV_FileArray, 2)).Value = Partitioned_CSV_FileArray ' Display Partitioned_CSV_FileArray to sheet

But this isn't working, so I'm still trying to work it out?!

thanks

JamSand
 
Upvote 0
Hi @johnnyL

Many thanks for posting this fantastic LoadCSV_FileToSheet() script, it works like a dream. For my usage, I'm trying to work out how to amend the script, so any imported files are appended to the end of any existing data, but I've not been able to work it out as yet.

I've stopped my worksheet from being cleared and also remove any duplicate data at the end of the script.

I've added the following lines to work out the last line of date + 1.

DataLRow = (ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row) + 1
DataLRowA = "A" & DataLRow

And changed

wsDestination.Range("B2").Resize(UBound(Partitioned_CSV_FileArray, 1), UBound(Partitioned_CSV_FileArray, 2)).Value = Partitioned_CSV_FileArray

to

wsDestination.Range(DataLRowA).Resize(UBound(Partitioned_CSV_FileArray, 1), UBound(Partitioned_CSV_FileArray, 2)).Value = Partitioned_CSV_FileArray ' Display Partitioned_CSV_FileArray to sheet

But this isn't working, so I'm still trying to work it out?!

thanks

JamSand

Hi @johnnyL

Many thanks for posting this fantastic LoadCSV_FileToSheet() script, it works like a dream. For my usage, I'm trying to work out how to amend the script, so any imported files are appended to the end of any existing data, but I've not been able to work it out as yet.

I've stopped my worksheet from being cleared and also remove any duplicate data at the end of the script.

I've added the following lines to work out the last line of date + 1.

DataLRow = (ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row) + 1
DataLRowA = "A" & DataLRow

And changed

wsDestination.Range("B2").Resize(UBound(Partitioned_CSV_FileArray, 1), UBound(Partitioned_CSV_FileArray, 2)).Value = Partitioned_CSV_FileArray

to

wsDestination.Range(DataLRowA).Resize(UBound(Partitioned_CSV_FileArray, 1), UBound(Partitioned_CSV_FileArray, 2)).Value = Partitioned_CSV_FileArray ' Display Partitioned_CSV_FileArray to sheet

But this isn't working, so I'm still trying to work it out?!

thanks

JamSand
Ah... just found the issue with my added code... argh... it was my delete duplicates code that needed changing. All sorted and working now.
 
Upvote 0

Forum statistics

Threads
1,214,918
Messages
6,122,246
Members
449,075
Latest member
staticfluids

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top