根据另一列中的值向上连接数据

时间:2019-03-26 11:25:24

标签: excel vba

我有A列和B列中的数据。我想获得C列中的数据。

是否可以通过使用VBA获得相同的结果?我无法向上循环。

谢谢。

+----------+----------+----------+
| Column A | Column B | Column C |
+----------+----------+----------+
| a        |          |          |
| b        |          |          |
| c        |          |          |
| d        |        1 | a,b,c,d  |
| x        |          |          |
| y        |          |          |
| z        |        2 | y,z      |
| s        |          |          |
| d        |          |          |
| e        |        3 | s,d,e    |
+----------+----------+----------+

2 个答案:

答案 0 :(得分:0)

类似这样的东西

Sub v()

Dim r As Excel.Range
Dim l As Long
Dim lRows As Long
Dim lNum As Long

Set r = Range("a1:b10")

l = 1

Do Until l > r.Rows.Count

    lNum = r.Cells(l, 2).End(xlDown).Row
    lRows = (lNum - l) + 1
    r.Cells(lNum, 3).Value = _
        Join(Application.Transpose(r.Cells(l, 1).Resize(lRows, 1)), ",")
    l = lNum + 1

Loop

End Sub

答案 1 :(得分:0)

您可以尝试:

Option Explicit

Sub trst()

    Dim LastRow As Long, i As Long
    Dim str As String

    With ThisWorkbook.Worksheets("Sheet1")

         LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

         For i = 2 To LastRow

            If .Range("B" & i).Value = "" Then

                If str = "" Then
                    str = .Range("A" & i).Value
                Else
                    str = str & ", " & .Range("A" & i).Value
                End If

            Else

                .Range("C" & i).Value = str & ", " & .Range("A" & i).Value
                str = ""

            End If

         Next i

    End With

End Sub