0

I want to reference Sheets within a Workbook via an index. - essentially as I want to run through a loop and clear certain cells on several worksheets.

At present I've written some vba which includes code like:

Sheet36.Activate Range("B3:T201").ClearContents

repeated each time for each sheet, for instance: Sheet37.Activate Range("B3:T201").ClearContents

All answers appreciated.

1
  • So, you want to loop through each sheet and then use an if statement or case select statement to determine what to clear on any given sheet? Commented Sep 9, 2015 at 16:34

2 Answers 2

1

If you have just a few sheets that you wish to clear a range on, it's easy to reference them all at the same time like so:

Sheets(Array("Sheet36", "Sheet37").Range("B3:T201").ClearContents

But if you really want to loop all of the sheets, then this is how:

Dim sh
For Each sh In Worksheets
    sh.Range("B3:T201").ClearContents
Next
Sign up to request clarification or add additional context in comments.

Comments

0

Clarification added thanks to ExcelHero.

You could use a Collection of the specific worksheets you are interested in. Something like:

Private mChosenSheets As Collection

Sub Init()
    Set mChosenSheets = New Collection
    
    ' Add here whichever worksheets you want in your iterable list
    mChosenSheets.Add Sheet6
    mChosenSheets.Add Sheet36
    mChosenSheets.Add Sheet38
    ' etc...
    
End Sub

Sub ClearChosenSheets()
    Dim sht As Worksheet
    
    For Each sht In mChosenSheets
        sht.Range("B3:T201").ClearContents
    Next
    
End Sub

The Workbook.Worksheets collection can be used if you just want to iterate through every worksheet in the workbook.

3 Comments

Each worksheet in a workbook is already a member of two built-in collections: Sheets and Worksheets. What would be the purpose of overtly adding them to another collection with regards to this question?
I don't think the Op wants to iterate through the Worksheets collection of the Workbook object (ie every worksheet sheet). I think he wants to iterate through a list he's generated of specific worksheets (ie only some sheets). This answer was meant to show him a way of adding just those worksheets to his own iterable collection.
Thanks All. Second solution fits my need better (as i only want to clear certain sheets).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.