2014-03-13 68 views
0

我不知道VB,所以我搜索並複製這個宏,以完成我的需要追加所有行的數據從同一工作簿中的工作簿從第10行到工作表。 我需要修改宏,以便將數據從第10行開始添加到主表中,因爲在第1-9行中有標題。Excel追加數據到主表

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行開始粘貼?

+0

'LastRow'的代碼是什麼樣的?如果我不得不猜測,我會說它應該尋找第一個空行。根據裏面的內容,如果需要,你可以在開始時強制這條線爲10:'Last = LastRow(DestSh)' –

回答

0

看起來好像您的代碼通過名爲LastRow的自定義函數來確定DestSh中的最後一行。因此,您似乎需要更改該函數中的某些內容,以避免覆蓋最初的第一行。

雖然我們不知道做什麼你的數據完全相同的樣子,我希望你能避免使用LastRow功能,而是replase行With DestSh.Cells(Last + 1, "A") 這一行:

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

這將找到的最後一個空列中的行ADestSh中,並粘貼複製範圍。