Excel将包含数据的所有行附加到母版中

时间:2014-03-13 11:12:48

标签: excel-vba vba excel

我不知道VB所以我搜索并复制了这个宏来完成我需要将所有行与来自第10行的同一工作簿中的工作表的数据附加到主工作表中。 我需要修改宏,以便从第10行开始将数据附加到主表中,因为在行1-9中有标题。

Sub CopyDataWithoutHeaders()
    Dim sh As Worksheet
    Dim DestSh As Worksheet
    Dim Last As Long
    Dim shLast As Long
    Dim CopyRng As Range
    Dim StartRow As Long

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Delete the sheet "RDBMergeSheet" if it exist
    Application.DisplayAlerts = False
    On Error Resume Next
    ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    'Add a worksheet with the name "RDBMergeSheet"
    Set DestSh = ActiveWorkbook.Worksheets.Add
    DestSh.Name = "RDBMergeSheet"

    'Fill in the start row
    StartRow = 10

    'loop through all worksheets and copy the data to the DestSh
    For Each sh In ActiveWorkbook.Worksheets

        'Loop through all worksheets except the RDBMerge worksheet and the
        'Information worksheet, you can ad more sheets to the array if you want.
        If IsError(Application.Match(sh.Name, _
                                     Array(DestSh.Name, "Information"), 0)) Then

            'Find the last row with data on the DestSh and sh
            Last = LastRow(DestSh)
            shLast = LastRow(sh)

            'If sh is not empty and if the last row >= StartRow copy the CopyRng
            If shLast > 0 And shLast >= StartRow Then

                'Set the range that you want to copy
                Set CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast))

                'Test if there enough rows in the DestSh to copy all the data
                If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                    MsgBox "There are not enough rows in the Destsh"
                    GoTo ExitTheSub
                End If

                'This example copies values/formats, if you only want to copy the
                'values or want to copy everything look below example 1 on this page
                CopyRng.Copy
                With DestSh.Cells(Last + 1, "A")
                    .PasteSpecial xlPasteValues
                    .PasteSpecial xlPasteFormats
                    Application.CutCopyMode = False
                End With

            End If

        End If
    Next

ExitTheSub:

    Application.GoTo DestSh.Cells(1)

    'AutoFit the column width in the DestSh sheet
    DestSh.Columns.AutoFit

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub

有人可以告诉我有关要从第10行开始粘贴的更改内容吗?

1 个答案:

答案 0 :(得分:0)

您的代码似乎从名为DestSh的自定义函数中确定LastRow中的最后一行。因此,您似乎需要更改该函数中的某些内容,以避免覆盖您的前10行。

虽然我们不知道您的数据究竟是什么样子,但我希望您可以避免使用LastRow函数,而是使用以下行替换行With DestSh.Cells(Last + 1, "A")

With DestSh.Cells(DestSh.Cells(Rows.Count, 1).End(xlUp).Row + 1, "A")

这将在A中找到DestSh列的最后一行空行,然后将复制的范围粘贴到那里。