Search code examples
excelvbacomboboxuserform

Load CSV to select sheets from combobox


I have UserForm With two things. Combobox with names of months and button to load CSV file to selected month from comboboxlist. When I uploaded my CSV file, always data prints in Sheet(12).

I want to create UserForm to upload CSV file to selected Sheet form ComboBox list.

For now in excel file is 12 sheets with name of months. Maybe i need to combine my name of sheets with this .AddItem ?

Private Sub Userform_Initialize()

Dim month(12) As String
    Dim i As Integer
        month(1) = "Styczeń"
        month(2) = "Luty"
        month(3) = "Marzec"
        month(4) = "Kwiecień"
        month(5) = "Maj"
        month(6) = "Czerwiec"
        month(7) = "Lipiec"
        month(8) = "Sierpień"
        month(9) = "Wrzesień"
        month(10) = "Październik"
        month(11) = "Listopad"
        month(12) = "Grudzień"

Dim ws As Worksheet
For i = 1 To 12

UseForm_START.Dane_miesiac.AddItem month(i)

Next i

End Sub

Private Sub CommandButton1_Click()
    
    Dim SciezkaPliku As Variant
    Dim FileFilter As String
    
    
    FileFilter = "Pixolus CSV (*.csv),*.csv"
    SciezkaPliku = Application.GetOpenFilename(FileFilter)
    

    With ThisWorkbook.Sheets(month(i)).QueryTables.Add(Connection:="TEXT;" & SciezkaPliku, Destination:=ThisWorkbook.Sheets(month(i)).Range("$A$2"))
    
        .Name = "CAPTURE"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlOverwriteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
        ActiveWorkbook.Save

    End With
    
    MsgBox "Dane zostały dodane!"
    
    'Worksheets("month(i)").Columns("D").Replace _ '
    'What:=".", Replacement:=",", _                 '
    'SearchOrder:=xlByColumns, MatchCase:=True      '
    'Worksheets("month(i)").Columns("D").Select     '
    'Selection.NumberFormat = "0.00"        '
End Sub

Solution

  • In CommandButton1_Click() try changing all occurances of month(i) with Me.Dane_miesiac.Value. Also I advise you to get in the habbit of using Option Explicit at the top of all your modules. You can do this manually or check "Require Variable Declaration" in "Tools/Options"