I am trying to build the source array in the consolidate function using VBA and then execute that function. However, I'm getting a 1004 runtime error ("Consolidate method of Range class failed."). Can someone please tell me what I'm doing wrong?
I have a named range in each worksheet for the same range of cells that I'm trying to consolidate into the worksheet called "Total". The named ranges are all named "Total_xxx", where xxx is the name of the worksheet. The only exception is the named range on the "Total" sheet and if there are any sheets with a "-", the named range replaces the "-" with "_".
When I open the workbook, I'm building a public global variable called strConsolidate to be the source for the consolidate statement.
Here is the code in the open workbook event:
When I query the strConsolidate string in the immediate window after this routine, it looks right -- like this:
Here is the code to execute the consolidate function, where it bombs out:
I have a named range in each worksheet for the same range of cells that I'm trying to consolidate into the worksheet called "Total". The named ranges are all named "Total_xxx", where xxx is the name of the worksheet. The only exception is the named range on the "Total" sheet and if there are any sheets with a "-", the named range replaces the "-" with "_".
When I open the workbook, I'm building a public global variable called strConsolidate to be the source for the consolidate statement.
Here is the code in the open workbook event:
Code:
Private Sub Workbook_Open()
' Purpose: Prepare statement for running the consolidate command.
Dim ws As Worksheet, booFlag As Boolean
booFlag = True
strConsolidate = "Array("
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> "Total" Then
If booFlag Then
strConsolidate = strConsolidate & """Total_" & ws.Name & """"
booFlag = False
Else
strConsolidate = strConsolidate & ", ""Total_" & ws.Name & """"
End If
End If
Next
strConsolidate = strConsolidate & ")"
strConsolidate = Replace(strConsolidate, "-", "_")
End Sub
When I query the strConsolidate string in the immediate window after this routine, it looks right -- like this:
HTML:
Array("Total_30001", "Total_30002", "Total_30003", "Total_30004", "Total_30005", "Total_30006", "Total_30007", "Total_30008", "Total_30009", "Total_30010", "Total_32004", "Total_32008", "Total_88002", "Total_88014", "Total_88022", "Total_88022_Init", "Total_88031", "Total_88047", "Total_88048", "Total_88051", "Total_88061")
Here is the code to execute the consolidate function, where it bombs out:
Code:
Public strConsolidate As String
Sub ConsolidateTotals()
' Purpose: Consolidate data on Total Sheet.
Sheets("Total").Select
Range("C2").Select
Selection.Consolidate Sources:=strConsolidate, _
Function:=xlSum, TopRow:=True, LeftColumn:=True, CreateLinks:=False
End Sub