如何在vba循环中连接变量名?

时间:2014-04-30 17:30:23

标签: vba access-vba

我正在尝试比较2个数组中的项目。如果第一个数组中存在一个项而第二个数组不存在,那么我想显示其值。但我正在努力做到这一点 - 我目前的尝试如下:

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

如果array1中的3个项目在array2中不匹配,那么我的标签显示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

我的循环中的逻辑有问题 - 你能帮我找到并修复错误吗?

2 个答案:

答案 0 :(得分: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

您在循环中构建不匹配项的字符串,然后在结尾处打印整个结果。

答案 1 :(得分: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