Create Excel Consolidated Worksheet with multiple sources in VBA

旧街凉风 提交于 2020-06-18 04:26:48

问题


I am trying to Consolidate multiple Worksheets on one Worksheet using VBA. How do I tell VBA to only consolidate the worksheets that are visible?


回答1:


I took Jerry Sullivan's answer from http://www.mrexcel.com/forum/excel-questions/620641-using-visual-basic-applications-perform-consolidate-function.html and tweaked it. The MSDN site was of some help in understanding the arguments, for example that the array of ranges must contain fully qualified addresses in R1C1 style.

Of course you gave no details on how you are trying to use Consolidate so this answer is generic. It consolidates the used range from all visible sheets in the active workbook using the Sum function:

Sub Consolidate_Totals()
    Dim ws As Worksheet
    Dim sArray As Variant, i As Integer
    ReDim sArray(1 To 1)

    '---Make Array with Named Ranges to be Consolidated
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Visible And ws.Name <> "Sheet1" Then
            i = i + 1
            ReDim Preserve sArray(1 To i)
            sArray(i) = ws.UsedRange.Address(ReferenceStyle:=XlReferenceStyle.xlR1C1, external:=True)
        End If
    Next ws
    If i = 0 Then Exit Sub

    '---Consolidate using the Array
    Sheets("Sheet1").Range("A1").Consolidate Sources:=(sArray), _
        Function:=xlSum, TopRow:=False, LeftColumn:=False, CreateLinks:=False
End Sub


来源:https://stackoverflow.com/questions/39425571/create-excel-consolidated-worksheet-with-multiple-sources-in-vba

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