循环遍历excel中的两行数据以匹配单元格并将字符串添加到vba中的新单元格

时间:2012-11-13 15:55:55

标签: vba excel-vba excel

我有一列唯一值(A)和第二组列,其中包含来自唯一值集(B)和另一个值(C)的值。

基本上我要做的是循环遍历所有唯一值A,然后有一个内部循环通过B,它可以多次从A中获得相同的值,并且每次找到匹配时,添加将值(C)连接到串联字符串,然后在找到所有这些值时,将其插入新单元格并继续下一个A值并执行相同操作。

我遇到了各种各样的错误并尝试了这几种方法,但根本没有经常使用VBA,我没有到达那里并且没有找到任何关于此的好信息。

有关如何执行此操作的任何帮助或想法都会有所帮助,下面是我正在使用的代码。

这基本上就是电子表格的样子

Column A ----- Column B -------- Column C 

A-----------------A---------------stringA  
A-----------------A --------------stringB
C-----------------B---------------stringC

所以在我的新专栏中,在A列旁边我会插入stringA,stringB。

希望这是有道理的。

Sub contactStuff()
    Dim roleName As String
    Dim rowNumber As Integer
    Dim userName As String
    Dim userRoleName As String
    Dim concatString As String
    Dim roleNumber As Integer
    roleNumber = 2
    rowNumber = 2
    For Each c In Worksheets("parentRoles").Range("C2:C856").Cells
        roleName = c.Value
        Do
            userRoleName = Worksheets("parentRoles").Range("G" & rowNumber)
            If userRoleName = roleName Then
                contactString = concatString & ", " & Worksheets("parentRoles").Range("E" & rowNumber)
                rowNumber = rowNumber + 1
            End If
        Loop While userRoleName = roleName
        Worksheets("parentRoles").Range("D" & roleNumber).Value = concatString
    Next
End Sub

1 个答案:

答案 0 :(得分:0)

Sub Button1_Click()
    Dim a As Long
    Dim b As Long
    Dim colA As Long
    Dim colB As Long
    Dim newString As String

    ' gets the last row in a column '
    colA = ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
    colB = ActiveSheet.Cells(ActiveSheet.Rows.Count, 2).End(xlUp).Row

    With Worksheets("Sheet1")
        ' First loop takes you through each unique value in column A '
        For a = 1 To colA
            newString = ""
            ' For every unique value in column A loop through column B and get the value from column C to build your string '
            For b = 1 To colB
                If .Cells(b, 2) = .Cells(a, 1) Then
                    If newString <> "" Then
                        newString = newString & ", " & Cells(b, 3) ' gets the value from col C and adds it to your new string '
                    Else
                        newString = Cells(b, 3)
                    End If
                End If
            Next
            ' Place the new string in column D'
            .Cells(a, 4).Value = newString
        Next
    End With
End Sub

使用以下列:

Col A   Col B   Col C
a         a       1 
b         b       1 
c         c       1 
          a       2 
          b       2 
          c       2 
          a       3 
          b       3 
          c       3 

您最终会在Col D中得到以下输出:

1, 2, 3
1, 2, 3
1, 2, 3