如何搜索特定的单元格值并与上面的行连接

时间:2018-04-22 21:47:12

标签: vba excel-vba concatenation row excel

我有一个Excel电子表格,其中的地址不一致。我想编写vba代码,在A列中搜索单词“UNIT”,然后将其与上面的地址行连接起来。我确信这是关闭的,但是像:

  sub ConcatenateRowAbove()
    Dim aCell as Range
    Dim lrow as Range
    Dim ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
 'find last row in column A which has data

    lrow = .range("A" & Rows.Count).End(xlUp).Row

'loop through each cell in column A and find text "UNIT" then concatenate with address in row above

    For Each aCell in .Range("A" & lrow)

       If acell.value = "UNIT" Then _

       aCell.FormulaR1C1 = "=CONCATENATE(R[-1]C[1])"

    Next aCell

      End With

      End Sub

示例:

101 E Main St

UNIT 1

102 E Main St

103 E Main St

104 E Main St

UNIT 1

104 E Main St

UNIT 2

结果:B列显示为Concatenated IF,有一个单位地址:

101 E Main St,UNIT 1

102 E Main St

103 E Main St

104 E Main St,UNIT 1

104 E Main St,UNIT 2

1 个答案:

答案 0 :(得分:0)

循环从下到上,连接然后删除。

Dim lrow as long, i as long
Dim ws As Worksheet

Set ws = ThisWorkbook.workSheets("Sheet1")

With ws
    'find last row in column A which has data
    lrow = .range("A" & .Rows.Count).End(xlUp).Row

    'loop through each cell in column A and find text "UNIT" then concatenate with address in row above

    For i=lrow to 2 step -1
        If lcase(left(.cells(i, "A").value2, 4)) = "unit" Then
            .cells(i-1, "A") = .cells(i-1, "A").value2 & " " & .cells(i, "A").value2
            .rows(i).entirerow.delete
        end if
    next i
End With