从一个模块中的集合获取值到userform中的combobox中

我有一个工作表,数据在“EGM”列中。 我的代码保存在该列中的值在集合中。 如果集合中只有一个值,则variablessSelectedEGM等于此值。 但是,如果有多个值,用户应该有可能只select一个值(我想在combobox中做到这一点),并将选定的项目保存到variablessSelectedEGM。

我的问题是,我不能从这个集合的值到userform。 当我的代码进入使用状态时,出现“types不匹配”的错误。 我在工作表中的代码:

Public sSelectedEGM As String Public vElement As Variant Public cEGMList As New VBA.Collection Sub kolekcjaproba() ' =================================== ' LOOP THROUGH EGMS AND WRITE THEM INTO COLLECTION ' =================================== Dim iOpenedFileFirstEGMRow As Integer Dim iOpenedFileLastEGMRow As Integer Dim iOpenedFileEGMColumn As Integer Dim iOpenedFileEGMRow As Integer Dim sOpenedFileEGMName As String Dim ws As Worksheet Dim wb As Workbook Set wb = ThisWorkbook Set ws = wb.Worksheets(1) iOpenedFileFirstEGMRow = Cells.Find("EGM").Offset(1, 0).Row iOpenedFileLastEGMRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, iOpenedFileFirstEGMRow).End(xlUp).Row iOpenedFileEGMColumn = Cells.Find("EGM").Column For iOpenedFileEGMRow = iOpenedFileFirstEGMRow To iOpenedFileLastEGMRow sOpenedFileEGMName = Cells(iOpenedFileEGMRow, iOpenedFileEGMColumn).Value For Each vElement In cEGMList If vElement = sOpenedFileEGMName Then GoTo NextEGM End If Next vElement cEGMList.Add sOpenedFileEGMName NextEGM: Next If cEGMList.Count = 1 Then sSelectedEGM = cEGMList.Item(1) ElseIf cEGMList.Count = 0 Then MsgBox "No EGM found" Else Load UserForm1 UserForm1.Show End If End Sub 

而我的代码在一个用户表单(只有一个combobox)

 Private Sub UserForm_Initialize() For Each vElement In cEGMList UserForm1.ComboBox1.AddItem vElement Next vElement End Sub Private Sub ComboBox1_Change() If ComboBox1.ListIndex <> -1 Then sSelectedEGM = ComboBox1.List(ComboBox1.ListIndex) End If End Sub 

您必须在标准模块中将cEGMList和sSelectedEGM声明为public,而不是在工作表模块中声明。

或者甚至更好:在表单上为集合和返回的值创build一个属性。 尽可能地避免全局variables总是更好的。

这是一个简单的例子。 在表单中,你可以定义像这样的属性和方法:

 Option Explicit Public TestProperty As Integer Public Sub TestMethod() MsgBox (TestProperty) End Sub Public Function TestMethodWithReturn() As Integer TestMethodWithReturn = TestProperty * 2 End Function 

在表单之外,您可以将其用作表单的常规属性/方法:

 Private Sub Test() Dim retValue As Integer UserForm1.TestProperty = 123 UserForm1.Show vbModeless UserForm1.TestMethod retValue = UserForm1.TestMethodWithReturn Debug.Print retValue End Sub