0

I'm trying to get a loop function to refer to a range of cells, rather than typing in the worksheet names individually.

I've got this code that works:

Sub LoopTest()
'
' Macro4 Macro
'

'
' Loop Test

Dim SheetsArray As Variant
Dim i As Integer
SheetsArray = Array("Bun1", "Bun2")

For i = LBound(SheetsArray) To UBound(SheetsArray)
    With Worksheets(SheetsArray(i)).Select
        Range("A2:G60").Select
        Selection.ClearContents
    End With
Next i

End Sub

But then this code doesn't when I try and get it to refer to a range instead:

Sub LoopTest()
'
'
' Loop Test

Dim Arr As Variant
Dim i As Integer
Dim rng As Range

Set rng = Worksheets("Names").Range("A2:A3")

Arr = rng

For i = LBound(Arr) To UBound(Arr)
    With Worksheets(Arr(i)).Select
        Range("A2:G60").Select
        Selection.ClearContents
    End With
Next i

End Sub

I'm getting "Subscript out of range" error when I try and use it, however the worksheets all exist (the range has the same names as the first code). Debug is highlighting the

WIth Worksheets(Arr(i)).Select

line. Any help would be greatly appreciated!

-Cr1kk0

1 Answer 1

3

You always get a 2 dimensional array when you assign a range to a variant so you need to specify both dimensions. There's also no need to select anything here:

For i = LBound(Arr, 1) To UBound(Arr, 1)
    Worksheets(Arr(i, 1)).Range("A2:G60").ClearContents
Next i
Sign up to request clarification or add additional context in comments.

2 Comments

Worked flawlessly. Thank you! Sorry, I don't have the reputation yet to upvote your answer.
You answer saved my life .

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.