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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.