合并多个工作表中的表

时间:2019-03-18 02:42:46

标签: arrays vba concatenation

Option Explicit

Sub Macro70()

Dim wb As Workbook
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim sheets_Count As Integer
Dim sheets_Name() As String
Dim i As Integer
sheets_Count = Sheets.Count

ReDim sheets_Name(0 To sheets_Count - 1)

For i = 1 To sheets_Count
   sheets_Name(i - 1) = "'" & ActiveWorkbook.Sheets(i).Name & "'!R1C1:R17C2"
Next i

Set wb = ThisWorkbook
Set ws2 = wb.Sheets.Add()

With ws2
    .Range("A1").Consolidate sheets_Name, xlSum, True, True, False
End With

End Sub


Sub Macro71()

Dim wb As Workbook
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim sheets_Count As Integer
Dim sheets_Name() As String
Dim i As Integer
sheets_Count = Sheets.Count

ReDim sheets_Name(0 To sheets_Count - 1)

For i = 1 To sheets_Count
   sheets_Name(i - 1) = "'" & ActiveWorkbook.Sheets(i).Name & "'!R24C1:R35C2"
Next i

Set wb = ThisWorkbook
Set ws2 = wb.Sheets.Add()

With ws2
    .Range("A24").Consolidate sheets_Name, xlSum, True, True, False
End With

End Sub


Sub Macro72()

Dim wb As Workbook
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim sheets_Count As Integer
Dim sheets_Name() As String
Dim i As Integer
sheets_Count = Sheets.Count

ReDim sheets_Name(0 To sheets_Count - 1)

For i = 1 To sheets_Count
   sheets_Name(i - 1) = "'" & ActiveWorkbook.Sheets(i).Name & "'!R39C1:R50C2"
Next i

Set wb = ThisWorkbook
Set ws2 = wb.Sheets.Add()

With ws2
    .Range("A39").Consolidate sheets_Name, xlSum, True, True, False
End With

End Sub

这对我来说非常合适,但是我必须说的最后一个问题是它会生成新的工作表。我可以在同一张纸上收集所有这些表的数据吗? 我尝试将ws2.Name =“ consolidated”放到所有三个文件夹中,但显示错误。我希望将sub 71和72与sub 70放入同一张纸中。并且感谢您提供的大量帮助。

1 个答案:

答案 0 :(得分:0)

我认为您需要这样的东西(未经测试)

sheets_Count = Sheets.Count

ReDim sheets_Name(0 to sheets_Count-1)

For i = 1 To sheets_Count
   sheets_Name(i-1) = "'" & ActiveWorkbook.Sheets(i).Name & "'!R10C1:R26C2"
Next i

Set wb = ThisWorkbook 
Set ws2 = wb.Sheets.Add()

With ws2
    .Range("A1").Consolidate sheets_Name, xlSum, True, True, False
End With

请参阅:

https://docs.microsoft.com/en-us/office/vba/api/excel.range.consolidate

这是该链接中的示例:

Worksheets("Sheet1").Range("A1").Consolidate _ 
            Sources:=Array("Sheet2!R1C1:R37C6", "Sheet3!R1C1:R37C6"), _ 
            Function:=xlSum

编辑-如果要在每个工作表中添加多个范围,可以尝试以下操作:

Dim n
sheets_Count = Sheets.Count

ReDim sheets_Name(0 To (sheets_Count * 2) - 1)
n = 0
For i = 1 To sheets_Count
   sheets_Name(n) = "'" & ActiveWorkbook.Sheets(i).Name & "'!R10C1:R26C2" 
   sheets_Name(n+1) = "'" & ActiveWorkbook.Sheets(i).Name & "'!R40C1:R50C2"
   n = n + 2
Next i