将多行(一个col)合并为一个(最后一行),并删除以前的行

时间:2015-10-09 08:54:28

标签: excel vba

我创建了一个Excel宏,用于将所有选定多行的内容合并到最后一行,如下面的代码所示:

Sub asdf()

    Dim rCell As Range
    Dim rRng As Range
    Dim rslt As String
    Dim lastCell As Range
    Dim i As Integer

    Set rRng = Range(Selection.Address)

    For Each rCell In rRng.Cells
        Debug.Print rCell.Address, rCell.Value
        rslt = rslt & " " & rCell.Value
        rslt = Trim(rslt)
        rCell.Value = rslt
    Next rCell

End Sub

问题是,如何删除除最后一行之外的所有多个(整个)行?

1 个答案:

答案 0 :(得分:1)

你可以试试这个

Sub asdf()
    Dim delCell as Range
    Dim rCell As Range
    Dim rRng As Range
    Dim rslt As String
    Dim lastCell As Range
    Dim i As Integer

    Set rRng = Range(Selection.Address)

    For Each rCell In rRng.Cells
        Debug.Print rCell.Address, rCell.Value
        rslt = rslt & " " & rCell.Value
        rslt = Trim(rslt)
        If Not rCell.Row = rRng.Row + rRng.Rows.Count - 1 Then
           If delCell is Nothing then
             set delCell = rCell
           Else
             set delcell = union(delCell, rCell)
           End If
        End If
        rCell.Value = rslt
    Next rCell
    delCell.EntireRow.Delete
End Sub