Excel vba匹配并在单独的标签中显示字段

时间:2015-07-23 12:47:25

标签: excel vba excel-vba

我坚持使用excel(多个)中的动态匹配字段,然后在每次匹配时更新标签的名称作为匹配。这是我找到的代码,但我似乎无法相应地编辑它,它匹配字段,但只在一个标签中显示它们之间的逗号。我希望每场比赛都在一个单独的标签中显示。 KR

Function MatchConcat(LookupValue, LookupRange As Range, ValueRange As Range)
    Dim lookArr()
    Dim valArr()
    Dim i As Long
    lookArr = LookupRange
    valArr = ValueRange
    For i = 1 To UBound(lookArr)
        If Len(lookArr(i, 1)) <> 0 Then
            If lookArr(i, 1) = LookupValue Then
            MatchConcat = MatchConcat & ", " & valArr(i, 1)
            End If
        End If
    Next
    MatchConcat = Mid(MatchConcat, 3, Len(MatchConcat) - 1)

End Function



   Dim var1 As String
var1 = MatchConcat(ComboBox3, Worksheets("Sheet5").Range("A:A"), Worksheets("Sheet5").Range("B:B"))
Label18.Caption = var1

1 个答案:

答案 0 :(得分:1)

  

首先,您需要启用Microsoft Scripting Runtime。   您可以在VBE中执行此操作,转到工具 - &gt;参考文献 - &gt;勾选Microsoft脚本运行时&#39;。

您可以将数组中的匹配项添加到字典中。然后,您可以遍历字典中的每个项目,并将每个项目分配给标签。

您需要将变量i调整为标签的起始编号。 i每次会增加1,并将其分配给每个标签。

你提到过ComboBox和Labels;我假设您在UserForm中引用了这些内容。您需要修改&#39; myUserForm&#39;到你的实际UserForm的名称。

Option Explicit
Sub MatchConcat()
    Dim wb As Workbook, ws As Worksheet
    Dim lookArr() As Variant, valArr() As Variant
    Dim i As Long, lastRow As Long
    Dim dict As Scripting.Dictionary, myItem As Variant
    Dim LookupValue As String

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")
    LookupValue = myUserForm.ComboBox3.Value

    With ws
        lastRow = .Cells(Rows.Count, 1).End(xlUp).Row
        lookArr = .Range(.Cells(1, 1), .Cells(lastRow, 1))
        valArr = .Range(.Cells(1, 2), .Cells(lastRow, 2))
    End With

    If lastRow > 1 Then
        Set dict = New Scripting.Dictionary
        For i = 1 To UBound(lookArr, 1)
            If lookArr(i, 1) = LookupValue Then
                dict.Item("Item" & valArr(i, 1)) = valArr(i, 1)
            End If
        Next i

        i = 18 'set to the name number of the first label
        For Each myItem In dict
            myUserForm.Controls("Label" & i).Caption = dict.Item(myItem)
            i = i + 1 ' increment i to line-up with labels numbers
        Next myItem
    End If
End Sub

编辑:根据评论中的问题,您可以通过在代码中包含以下内容来使组合框可见。同样,您必须确保ComboBox编号与迭代编号匹配。以下内容将替换上述代码中的底部For Each

i = 1 'set to the name number of the first label
For Each myItem In dict
    With myUserForm
        .Controls("Label" & i).Caption = dict.Item(myItem)
        .Controls("ComboBox" & i).Visible = True
        .Controls("ComboBox" & i & i).Visible = True
    End With
    i = i + 1 ' increment i to line-up with labels numbers
Next myItem

第一个标签需要调用Label1,第一个ComboBox需要调用ComboBox1ComboBox11