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
 

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.
Yes, but I would like to create a "button", to browse for .csv file and Import it to Sheet2, starting at B2 , knowing that the .csv delimiter is ;
 
Upvote 0
All I need in In Sheet1, is to INSERT a Command Button which BROWSE the .csv file, and IMPORT it on Sheet2, starting with cell B2 , knowing that data delimiter in .CSV file semicolumn ";" so I want to SPLIT it by ;
 
Upvote 0
See if the following code examples do what you asked for:

Code module that will perform when you click the Button:
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

And the code module to create your Button:
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

Add both of those modules, Run the 'CreateAClickableMacroButton' subroutine, after you adjust the settings within it, to create the button.

From then on, you just click the created button to select the CSV file to import.
 
Upvote 0
Forgot to mention the 'LoadCSV_FileToSheet' module gets added to the sheet code module that the Button is created on.
 
Upvote 0
Well, I am not good in VBA at all so if you could help PLEASE.
In my file, in Sheet1, I went in Design Mode then Insert then Command Button(ActiveX Control) then View Code
I got this :
Private Sub CommandButton1_Click()

End Sub

Could you please let me know what to Copy/Paste here ?

Again, want to BROWSE for .csv file, Import in Sheet2 starting at B2, text from .csv to be splited to columns (delimiter is semicolumn ;) ;)
Thank you again
 
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.
 
Upvote 0
Solution
Well, Super Thank you
I have follow the steps and all work perfect
 
Upvote 0
I would like to ask, in last VBA :
01.
ReDim Partitioned_CSV_FileArray(1 To UBound(All_CSV_RowsFromCSV_FileArray), 1 To 100)
100 is max of .csv rows or columns it can convert ?

02.
CSV_FileRowColumnsArray = Split(All_CSV_RowsFromCSV_FileArray(CSV_FileRow), ";")
Is this possible ? to replace ";" with value in Sheet1 cell A1 (so in A1 I can have "." or ";" or "," ......
 
Upvote 0

Forum statistics

Threads
1,215,063
Messages
6,122,928
Members
449,094
Latest member
teemeren

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