2014-04-30 39 views
-2

我想比较两个数组中的项。如果一个项目出现在第一个数组而不是第二个数组中,那么我想显示它的值。然而当我做到这一点的方式挣扎 - 我现在的尝试是下面:如何在vba循环中连接变量名?

Dim l1  As Long 
Dim l2  As Long 
Dim Size1 As Long 
Dim Size2 As Long 

' array1= listbox1 contents 
'array2 =listbox2 contents 

Size1 = UBound(array1) 
Size2 = UBound(array2) 
Dim bln As Boolean 

For l1 = 1 To Size1 
    bln = False 
    For l2 = 1 To Size2 
     If array1(l1) = array2(l2) Then 
      bln = True 
     End If 
    Next l2 
    If bln = False Then 
    Me.Label_nonmatchitems.Caption = "Do not have a match for item(s) " & l1  

    Next l1 

End sub 

如果阵列1的3项数组2不匹配,那么我的标签显示的是3次,这样的:

Do not have a match for item(s) value1 
Do not have a match for item(s) value8 
Do not have a match for item(s) value10 

相反,我一直在寻找这样的输出:

 Do not have a match for item(s) value1,value8,value10 

也有一些是错误的,在我的循环逻辑 - 你能帮我找到并修复错误?

+0

请澄清您的具体问题或添加其他详细信息,以突出显示您的需要。正如目前所写,很难确切地说出你在问什么。请参阅“如何问问”页面以获取有关澄清此问题的帮助。 –

+0

我编辑了这个问题 - 我想现在已经足够清楚了,它不需要关闭。 – Floris

+0

感谢您的更新 – vuyy1182

回答

2

修改代码如下:

Dim l1  As Long 
Dim l2  As Long 
Dim Size1 As Long 
Dim Size2 As Long 

Size1 = UBound(array1) 
Size2 = UBound(array2) 
Dim bln As Boolean 
Dim nonMatching As String 

nonMatching = "" 

For l1 = 1 To Size1 
    bln = False 
    For l2 = 1 To Size2 
     If array1(l1) = array2(l2) Then 
      bln = True 
     End If 
    Next l2 
    If bln = False Then 
    nonMatching = nonMatching & l1 & ", " 
    End If 
    Next l1 
    If Len(nonMatching) > 0 Then 
    nonMatching = Left(nonMatching, Len(nonMatching) - 2) ' strip final comma-space  
    Me.Label_nonmatchitems.Caption = "Do not have a match for item(s) " & nonMatching 
    Else 
    Me.Label_nonmatchitems.Caption = "All items match" 
    End If 

End Sub 

您打造循环不匹配项的字符串,然后在最后打印整个结果。

+0

* nonMatching = Left(nonMatching,Len(nonMatching) - 1)*无法去掉逗号。 – vuyy1182

+0

我不知道是否因为我实际上添加了'逗号,空格' - 所以你必须删除2个字符。另外,我想如果没有不匹配的值,那么没有什么可剥离的。所以你可能想要测试这个长度:'如果Len(nonMatching)> 0那么nonMatching = Left(nonMatching,Len(nonMatching) - 1)'。现在更新答案... – Floris

+1

完美!谢谢 – vuyy1182

0
"Do not have a match for item(s) " 

将此部分移至for循环的上方。

Text="Do not have a match for item(s) " 
For l1 = 1 To Size1 
    bln = False 
    ... 
    Text2 = Text2 & L1 
Next l1 

Me.Label_nonmatchitems.Caption = Text & Text2