Writing a dynamic Array in VBA

MS_Xsmell

Board Regular
Joined
Jan 27, 2007
Messages
76
Office Version
  1. 365
Platform
  1. Windows
Hey all, I'm using the Consolidate function to sum up a consistent range of data across multiple worksheets in a workbook. Here is my current code:
VBA Code:
Sub Consl()
      
'Consolidated Sheets
    Selection.Consolidate Sources:=Array( _
    "'1'!R3C4:R6c20", "'2'!R3C4:R6c20", "'3'!R3C4:R6c20", "'4'!R3C4:R6c20", "'5'!R3C4:R6c20", "'6'!R3C4:R6c20", "'7'!R3C4:R6c20", _
    "'8'!R3C4:R6c20", "'9'!R3C4:R6c20", "'10'!R3C4:R6c20"), _
    Function:=xlSum, TopRow:=True, LeftColumn:=True, CreateLinks:=False

End Sub

I would like to improve this by making the number of sheets in the array dynamic. As an example, if I have 30 sheets ( named sheet 1 through 30) I would like them to be included in the array. I tried going the route of defining the number of tabs I want to include in the array:
VBA Code:
For i = 1 To Range("TabCount")
I just can't figure out how to introduce it to the array.

Thanks in advance.
 

Excel Facts

Will the fill handle fill 1, 2, 3?
Yes! Type 1 in a cell. Hold down Ctrl while you drag the fill handle.
Maybe something like this:
VBA Code:
Sub SheetsArray()
Dim i As Long, myArray()
ReDim myArray(1 To Sheets.Count)
For i = 1 To Sheets.Count
    myArray(i) = i
Next i
'the sheet index numbers are in myArray
MsgBox Join(myArray, ", ")
'test to return name of the sheet with index number 6
MsgBox Sheets(myArray(6)).Name
End Sub
 
Upvote 0
Try this:

VBA Code:
Sub Cons_2()
  Dim i As Long, arr() As Variant
 
  ReDim arr(1 To 30)
  For i = 1 To UBound(arr)
    arr(i) = "'" & i & "'!R3C4:R6C20"
  Next
  Selection.Consolidate arr, xlSum, True, True, False
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,786
Messages
6,121,546
Members
449,038
Latest member
Guest1337

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top