用户表单初始化时,combobox未填充,但在closures和重新打开表单后填充

出于某种奇怪的原因,一旦表单被初始化,我的combobox就不会被“预加载”内容,用户必须首先closures表单,然后再次打开,以便combobox被预先填充。 这是一个开始激怒最终用户的错误,为什么会出现这种情况呢? 我已将Boot添加到电子表格中的一个button上,该button初始化表单。 代码如下:

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 

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

 Sub Boot() UserForm1.Show End Sub Private Sub UserForm_Initialize() Call GetPrimaryContact Call GetSecondaryContact End Sub 

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