简体   繁体   中英

Excel: Consolidating with VBA for variable worksheets

I have seen a lot of "consolidating" with VBA on the web, but mostly are copy and pasting from one sheet to another. I am trying to use excel's own consolidating tools, but in VBA. The thing is, the number of sheets can be from 3 to 100. So, it is not quite practical to choose the parameters one by one. Suppose each sheet has the same format, 3 columns. I would like to consolidate the last 2 columns (2 and 3). Each sheet has a specific naming convention, which is some_2015-??, where the last two are digits, in sequential manner (00~99). Consolidating function works admirably, just that needing to specify each range for each sheet is not practical.

Below is the macro I have recorded:

' Selection.Consolidate Sources:=Array("'[Book1]some_2015-01'!C2:C3", _ "'[Book1]some_2015-02'!C2:C3", "'[Book1]some_2015-03'!C2:C3"), Function:=xlSum _ , TopRow:=True, LeftColumn:=True, CreateLinks:=False '

2 questions in total, how do I make the array to adapt to the number of sheets? and I am specifying column B and C, but in the code, it is "C2:C3", does that mean the range is something else?

Try something like:

Sub ConsolidateSheets(n As Long)
    Dim A As Variant
    Dim i As Long
    ReDim A(0 To n - 1)
    For i = 0 To n - 1
        A(i) = "'[Book1]some_2015-" & Format(i + 1, "00") & "'!C2:C3"
        Debug.Print A(i)
    Next i
    Selection.Consolidate Sources:=A, Function:=xlSum, TopRow:=True, LeftColumn:=True, CreateLinks:=False
End Sub

n = 3 should reproduce your recorded macro. Obviously, Selection can be changed if needed. C2:C3 is columns B and C in R1C1 notation (which the Consolidate method demands). I'm not sure if the book reference is required. It would probably need to be changed if you rename the book. You could try just using

A(i) = "some_2015-" & Format(i + 1, "00") & "!C2:C3"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM