首页 文章

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

提问于
浏览
1

我有一个工作表,其中包含'EGM'栏中的数据 . 我的代码保存集合中此列的值 . 如果集合中只有一个值,则变量sSelectedEGM等于此值 . 但是如果有多个值,则用户应该只能选择一个值(我想在组合框中执行此操作)并将所选项目保存到变量sSelectedEGM中 .

我的问题是,我无法从此集合中获取值到userform . 当我的代码进入useform时,会出现错误“Type mismatch” . 我在工作表中的代码:

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

我在userform中的代码(只有一个组合框)

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

1 回答

  • 1

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

    甚至更好:在表单上为集合和返回值创建属性 . 尽可能避免全球变量总是更好 .

    这是一个简化的例子 . 在表单中,您可以定义属性和方法:

    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
    

相关问题