How to retrieve name of dynamically created ComboBox in VBA?

时间:2015-05-12 23:32:40

标签: excel forms vba excel-vba combobox

I would like to reference the value of ComboBoxes I created using a loop, but I do not know what their name is. How can I find their name?

    #include<fftw3.h>

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用从.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”的UserForm来验证这一点,并在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