合并和删除数据行

时间:2012-06-21 18:21:31

标签: excel vba excel-vba

我需要编写一个宏来清理Excel文档。我现在有大部分功能正常工作,但我无法将两行数据合并在一起。我需要先合并两行数据,然后删除第二行。这段代码来自我遇到问题的函数,我正在删除正确的行,但是我想首先将我要删除的行与上面的行合并在一起,这样就不会丢失任何数据;有没有人知道是否有快速命令将整行合并在一起,或者我必须逐个单元地进行。

For RowCount = Selection.Rows.Count To 1 Step -1

    ' Delete rows that don't have text in col A
    If Selection.Cells(RowCount, 1).Text <> "" And IsNumeric(Selection.Cells(RowCount, 1).Value) Then
        'Is Number


    ElseIf Selection.Cells(RowCount, 1).Text = "Heading" Then
        'Its the Heading
    Else

        'Its not needed!
        '*********************************************************
        'CODE TO MERGE TWO ROWS SHOULD GO HERE********************
        '(MERGE ROWCOUNT-1 WITH ROWCOUNT AND DELETE ROWCOUNT)*****
        '*********************************************************

        Selection.Rows(RowCount).EntireRow.Delete
    End If

' Start next iteration of RowCount loop.
Next RowCount

1 个答案:

答案 0 :(得分:1)

我认为你需要逐个细胞地进行。

替换:

'*********************************************************
'CODE TO MERGE TWO ROWS SHOULD GO HERE********************
'(MERGE ROWCOUNT-1 WITH ROWCOUNT AND DELETE ROWCOUNT)*****
'*********************************************************

使用:

Dim ColumnCount As Integer, intCnt As Integer
ColumnCount = Selection.columns.count

For intCnt = 1 To ColumnCount

    Dim strRow As String, strPrevRow As String
    strRow = Selection.Cells(RowCount, intCnt).Text
    strPrevRow = Selection.Cells(RowCount, intCnt).offset(-1).Text

    Selection.Cells(RowCount, intCnt).offset(-1) = strRow & " " & strPrevRow

Next