Excel vba匹配并显示在不同的标签中的字段

我坚持dynamic匹配字段在Excel中(不止一个),然后在每个匹配更新标签的名称作为匹配。 这是我find的代码,但我似乎不能编辑它相应的,它匹配的领域,但只显示在一个标签之间用逗号之间。 我希望每一场比赛都能在一个单独的标签上展示。 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 

首先,您需要启用Microsoft脚本运行时。 您可以通过在VBE中进行工具 – >参考 – >勾选“Microsoft脚本运行时”来完成此操作。

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

您需要将variablesi调整为标签的起始编号。 然后i会每增加1,将它的项目分配给每个标签。

你已经提到了ComboBox和Labels; 我假设你是指UserForm内的这些。 您需要将“myUserForm”修改为您的实际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可见。 再次,您必须确保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 ,而第一个ComboBoxes需要被称为ComboBox1ComboBox11