如何在 VBA 中检索动态创建的 ComboBox 的名称?

How to retrieve name of dynamically created ComboBox in VBA?

我想引用我使用循环创建的组合框的值,但我不知道它们的名称是什么。我怎样才能找到他们的名字?

Sub addLabel()
Dim theLabel As Object
Dim theRanker As Object
Dim labelCounter As Long
Dim RowCount As Integer

RowCount = Sheets("Overview").Range("A" & Rows.count).End(xlUp).Row

For labelCounter = 1 To RowCount
    Set theRanker = CriteriaPairwiseForm.Controls.Add("Forms.ComboBox.1", "Rating" & labelCounter, True)
    With theRanker
        .Left = 20
        .Width = 150
        .Top = 30 * labelCounter
        .AddItem "Equal Importance"
        .AddItem "Moderate Importance"
        .AddItem "Strong Importance"
        .AddItem "Very Strong Importance"
        .AddItem "Extreme Importance"

    End With
    Set theLabel = CriteriaPairwiseForm.Controls.Add("Forms.Label.1", "CriteriaRank" & labelCounter, True)
    With theLabel
        .caption = Cells(labelCounter, 1).Value
        .Left = 200
        .Width = 150
        .Top = 30 * labelCounter

    End With
Next labelCounter
End Sub

最简单的方法是使用从 .Add 方法中获得的引用来命名它们。您已经循环遍历了一系列值,因此使用循环计数器来构建对象名称。这样做的好处是还具有与标签来源的行相对应的名称:

Sub addLabel()
    Dim theLabel As Object
    Dim theRanker As Object
    Dim labelCounter As Long
    Dim RowCount As Integer

    RowCount = Sheets("Overview").Range("A" & Rows.Count).End(xlUp).Row

    For labelCounter = 1 To RowCount
        Set theRanker = CriteriaPairwiseForm.Controls.Add("Forms.ComboBox.1", _
                        "Rating" & labelCounter, True)
        With theRanker
            .Left = 20
            .Width = 150
            .Top = 30 * labelCounter
            .AddItem "Equal Importance"
            .AddItem "Moderate Importance"
            .AddItem "Strong Importance"
            .AddItem "Very Strong Importance"
            .AddItem "Extreme Importance"
            .Name = "Ranker" & labelCounter
        End With
        Set theLabel = CriteriaPairwiseForm.Controls.Add("Forms.Label.1", _
                       "CriteriaRank" & labelCounter, True)
        With theLabel
            .Caption = Cells(labelCounter, 1).Value
            .Left = 200
            .Width = 150
            .Top = 30 * labelCounter

        End With
    Next labelCounter
End Sub

稍后您可以使用相同的方法从它们中获取值(或通过连接名称按行索引寻址它们)。您可以通过创建一个名为 "CriteriaPairwiseForm" 的用户窗体并在窗体中添加以下代码来验证这一点 Sub addLabel:

Option Explicit

Private Sub UserForm_Initialize()
    addLabel
End Sub

Private Sub UserForm_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    GetValues
End Sub

Private Sub GetValues()

    Dim labelCounter As Long
    Dim RowCount As Integer
    Dim message As String

    RowCount = Sheets("Overview").Range("A" & Rows.Count).End(xlUp).Row

    For labelCounter = 1 To RowCount
        message = "Ranker" & labelCounter & " contains:" & vbCrLf & _
                  CriteriaPairwiseForm.Controls("Ranker" & labelCounter).Text
        MsgBox message
    Next labelCounter

End Sub