Search code examples
excelvbacomboboxuserform

Fill two ComboBoxes with table values


I have a UserForm that has two ComboBoxes.

Private Sub UserForm_Initialize()

''''''' Preencher com os bancos ''''''

    Dim i As Long
    Dim n As Long
    Dim sh As Worksheet
    
    Set sh = ThisWorkbook.Sheets("Spreads")

    n = sh.Range("A" & Application.Rows.Count).End(xlUp).Row

    For i = 2 To n
        Me.BancoBox.AddItem Cells(i, 1)
    Next i
    
''''''' Preencher com os fornecedores ''''''
    
    Dim y As Long
    Dim f As Long
    Dim forn As Worksheet
    
    Set forn = ThisWorkbook.Sheets("Fornecedores")
    
    f = forn.Range("A" & Application.Rows.Count).End(xlUp).Row
    
    For y = 2 To f
        Me.FornecedorBox.AddItem Cells(y, 1)
    Next y
    
End Sub

One ComboBox is for names of banks and the other is for names of suppliers which are in the "Spreads" and "Fornecedores" sheets accordingly.

They both return the name of the banks.


Solution

  • When adding the items you omitted a sheet reference so the active sheet was assumed. Since this does not change in your code the same sheet was referenced each time.

    Private Sub UserForm_Initialize()
    
    Dim i As Long
    Dim n As Long
    Dim sh As Worksheet
    
    Set sh = ThisWorkbook.Sheets("Spreads")
    n = sh.Range("A" & Application.Rows.Count).End(xlUp).Row
    
    For i = 2 To n
        Me.BancoBox.AddItem sh.Cells(i, 1) 'sheet reference
    Next i
    
    Dim y As Long
    Dim f As Long
    Dim forn As Worksheet
    
    Set forn = ThisWorkbook.Sheets("Fornecedores")
    f = forn.Range("A" & Application.Rows.Count).End(xlUp).Row
    
    For y = 2 To f
        Me.FornecedorBox.AddItem forn.Cells(y, 1) 'sheet reference
    Next y
        
    End Sub
    

    Note though that the quickest way to populate a combobox is to use List property and then you can avoid loops altogether, e.g.

    Me.FornecedorBox.List = forn.Range("A2:A" & f).Value