简体   繁体   English

将多个工作表合并为一个

[英]merge multiple worksheets into one

I'm trying to merge multiple worksheets into one summary sheet. 我正在尝试将多个工作表合并到一个摘要表中。
Each Worksheet has the name 'Table #number', for example Table 1 , Table 2 etc. The layout of each sheet is identical. 每个工作表的名称为“表编号”,例如Table 1Table 2等。每个表的布局相同。 Data range is columns A1 : N13 . 数据范围是A1 : N13列。
This function doesn't work: =SUM('Table 1':'Table 25'!$A$1:$N$13) . 此功能不起作用: =SUM('Table 1':'Table 25'!$A$1:$N$13)
How do I use VBA to amalgamate this data? 如何使用VBA合并这些数据?

在此处输入图片说明

This is a simplified example: 这是一个简化的示例:

Option Explicit

Sub amalgamateData()

'initialise result variable
Dim myResult As Double
myResult = 0

'loop through sheets to get the sum
Dim wks As Excel.Worksheet  'loop control variable
For Each wks In Excel.ThisWorkbook.Worksheets
    If Left(wks.Name, 5) = "Table" Then ' only the "Table" sheets
        With wks
            Dim rngTarget As Range
            myResult = myResult + Excel.Application.WorksheetFunction.Sum(.Range("A1:N13"))
        End With
    End If
Next

'add result to sheet "Result"
Excel.ThisWorkbook.Sheets("Result").Range("A1") = myResult

End Sub

My starting point was this SO Post : how-to-merge-data-from-multiple-sheets 我的出发点是这样的SO Post :如何从多个表中合并数据

As Siddharth saud - there loads of references for you on SO HERE IS A SEARCH FOR YOU ... CHECK OUT WHAT IS IN THE BOX IN THE TOP RIGHT OF THE SCREEN 正如Siddharth saud一样-在这里有大量参考文献可供您搜索...请查看屏幕右上方的框中的内容

Sub MergeSheet()

'Declaring the Variables
Dim LastRow, ShtCnt As Integer
Dim ShtName As String
Dim NewSht As Worksheet

'Assinging a Sheet Name by UserInput
ShtName:
ShtName = InputBox("Enter the Sheet Name you want to create", "Merge Sheet", "Master Sheet")

'Count of Total Worksheet in the present workbook
ShtCnt = Sheets.Count

'Using For Loop check if the worksheet exists
For i = 1 To ShtCnt
If Sheets(i).Name = ShtName Then
MsgBox "Sheet already Exists", , "Merge Sheet"
GoTo ShtName
End If
Next i

'Create a New Sheet
Worksheets.Add.Name = ShtName

'Assigning NewSht as Current Sheet
Set NewSht = ActiveSheet

'Moving Worksheet to the beginning of this workbook
NewSht.Move before:=Worksheets(1)

'Copying all the data to the New Sheet Using For Loop
For i = 2 To ShtCnt + 1

'If i=2 Then copy all the data from the second sheet including header.
If i = 2 Then
Sheets(i).UsedRange.Copy NewSht.Cells(1, 1)
Else

'If i is grater than 2 then copy all the data excluding Header(1st Row).
Sheets(i).UsedRange.Offset(1, 0).Resize(Sheets(i).UsedRange.Rows.Count - 1, Sheets(i).UsedRange.Columns.Count).Copy NewSht.Cells(LastRow + 1, 1)
End If
LastRow = NewSht.Cells.SpecialCells(xlCellTypeLastCell).Row
Next i

'Displaying the Message after copying data successfully
MsgBox "Data has been copied to " & ShtName, , "Merge Sheet"

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM