初始化用户表单时未填充Combobox,但在关闭并重新打开表单后填充

时间:2014-05-13 23:51:25

标签: forms excel vba excel-vba combobox

由于一些奇怪的原因,我的组合框不是预先加载的#34;对于内容,一旦表单初始化,用户必须首先关闭表单,然后再次打开它以便预先填充组合框。这是一个开始激怒最终用户的错误,不知道为什么会发生这种情况?我已将启动附加到我的电子表格中的按钮,该按钮会初始化表单。代码如下:

UserForm1

Private Sub UserForm1_Initialize()
    Call GetPrimaryContact
    Call GetSecondaryContact
End Sub

Module1

Public itm1
Public itm2

Sub Boot()

    UserForm1.Show
    Call GetPrimaryContact
    Call GetSecondaryContact

End Sub

Sub GetPrimaryContact()

    Dim Col As New Collection
    Dim i As Long
    Dim CellVal As Variant

    ' Clear filters

    ThisWorkbook.Sheets("Master").AutoFilter.ShowAllData

    ' Get last row

    LastRow = ThisWorkbook.Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row

    ' Loop between all of column F to get unique values

    For i = 3 To LastRow
        CellVal = ThisWorkbook.Sheets("Master").Range("F" & i).Value
        On Error Resume Next
        Col.Add CellVal, Chr(34) & CellVal & Chr(34)
        On Error GoTo 0
    Next i

    ' Populate the first with primary contacts

    For Each itm1 In Col
        With UserForm1.ComboBox1
            If IsEmpty(itm1) Then .AddItem "No Contact" Else .AddItem itm1
        End With
    Next

End Sub

Sub GetSecondaryContact()

    Dim Col As New Collection
    Dim i As Long
    Dim CellVal As Variant

    ' Clear filters

    ThisWorkbook.Sheets("Master").AutoFilter.ShowAllData

    ' Get last row

    LastRow = ThisWorkbook.Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row

    ' Loop between all of column F to get unique values

    For i = 3 To LastRow
        CellVal = ThisWorkbook.Sheets("Master").Range("G" & i).Value
        On Error Resume Next
        Col.Add CellVal, Chr(34) & CellVal & Chr(34)
        On Error GoTo 0
    Next i

    ' Populate the first with primary contacts

    For Each itm2 In Col
        With UserForm1.ComboBox2
            If Not IsEmpty(itm2) Then .AddItem itm2
        End With
    Next

End Sub

2 个答案:

答案 0 :(得分:1)

您应该在表单initialize事件上调用函数GetPrimaryContact和GetSecondaryContact,这样控件将按预期加载。请参阅下面的示例代码。

Sub Boot()

    UserForm1.Show

End Sub

Private Sub UserForm_Initialize()

    Call GetPrimaryContact
    Call GetSecondaryContact

End Sub

答案 1 :(得分:0)

我认为你的问题是你的Initialize代码有Userform1_Initialize。它应该只写为Userform_Initialize,它将起作用。 并且在Sub boot中将userform1.show放在最后而不是第一位,如果你踩到F8,你会看到当你来到FormShow它停在那里所以它不会加载你的“调用”,直到你关闭它,这就是为什么你有他们下一步你开始的时候。