用 table 值填充两个组合框

Fill two ComboBoxes with table values

我有一个包含两个组合框的用户窗体。

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

一个 ComboBox 用于银行名称,另一个用于供应商名称,相应地出现在“Spreads”和“Fornecedores”表中。

他们都是return银行的名字。

您应该先激活工作表,然后再对其执行任何操作。

添加项目时您省略了 sheet 引用,因此假定活动 sheet。由于这不会在您的代码中更改,因此每次都引用相同的 sheet。

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

请注意,填充组合框的最快方法是使用 List 属性 然后您可以完全避免循环,例如

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