Merge more than 3 Excel worksheets into one workbook with macro

不羁岁月 提交于 2020-01-06 16:22:20

问题


I'm trying to merge worksheets together into one workbook. I have a work book that has over 20 sheets. I was looking to create a macro that would merge sheets together (depending on their name) into a separate workbook.

So far this is the code that I have got: it mergers all the sheets in the workbook together but I would like to merge them by name.

Sub mergedata()
  Sheets(1).Activate
  lastrow = ActiveSheet.UsedRange.Rows.Count
  For Each Sheet In Sheets
    If Sheet.Index <> 1 Then
      RowCount = Sheet.UsedRange.Rows.Count
      Sheet.UsedRange.Copy Destination:=Sheets(1).Cells(lastrow + 1, 1)
      lastrow = lastrow + RowCount
      Sheet.UsedRange.Clear
    End If
  Next Sheet
End Sub

回答1:


You need to add one additional if statements in your loop. This could be like this:

'.....
For Each Sheet In Sheets
    If Sheet.Index <> 1 Then
        If Sheet.Name = "NameOfSheet" or Sheet.Name = "NameIsCaseSensitive" then
            RowCount = Sheet.UsedRange.Rows.Count
            Sheet.UsedRange.Copy Destination:=Sheets(1).Cells(lastrow + 1, 1)
            lastrow = lastrow + RowCount
            Sheet.UsedRange.Clear
        end if
    End If
Next Sheet
'....



回答2:


I case you need the same but horizontaly (like I did) (w/o Names upgrade)

Sub mergedata_horizontal()
  Sheets(1).Activate
  lastcol = ActiveSheet.UsedRange.Columns.Count
  For Each Sheet In Sheets
    If Sheet.Index <> 1 Then
      ColCount = Sheet.UsedRange.Columns.Count
      Sheet.UsedRange.Copy Destination:=Sheets(1).Cells(1, lastcol + 1)
      lastcol = lastcol + ColCount
      Sheet.UsedRange.Clear
    End If
  Next Sheet
End Sub


来源:https://stackoverflow.com/questions/19182360/merge-more-than-3-excel-worksheets-into-one-workbook-with-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!