2014-04-30 77 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