Using an integer to call next values

BritsBlitz

New Member
Joined
Jan 10, 2014
Messages
19
I have the following code to copy a select range of cells from one sheet and past it to another sheet when specific checkboxes are checked:
Rng1 = ("A4:I14")
Rng2 = ("A15:I26")

If Sheets("Setup").Cells(nbr, 3).Value = True Then
Sheets("TestPro").Range(Rng1).Copy
PasteValues
End If

This works fine but I would like to use a For loop so that I can copy and paste multiple ranges without having to retype the copy/paste command every time.

For instance, For nbr = 1 To 2, when nbr =1, I want to copy Range(Rng1). When nbr = 2, I want to copy Range(Rng2) etc. How can I use the nbr integer in my For loop to increase the "number" that follows Rng?
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
VBA doesn't allow you to build symbol names for variables in the way you are describing.
You could use If statements or Select Case statements but that's more complicated than it needs to be.

A similar approach that would achieve your objective would be to use arrays.
Something like...

Code:
Sub Test()
 Dim asRangeRefs() As String
 Dim nbr As Long
 
 ReDim asRangeRefs(1 To 3)
 
 asRangeRefs(1) = "A4:I14"
 asRangeRefs(2) = "A15:I26"
 asRangeRefs(3) = "A27:I38"
 
 For nbr = 1 To 3
   If Sheets("Setup").Cells(nbr, 3).Value = True Then
      Sheets("TestPro").Range(asRangeRefs(nbr)).Copy
      Sheets("Dest").Range(asRangeRefs(nbr)).PasteSpecial (xlPasteValues)
   End If
 Next nbr

End Sub

There's easier ways to populate an array, this example just tries to follow the approach you describe.
 
Upvote 0

Forum statistics

Threads
1,213,487
Messages
6,113,941
Members
448,534
Latest member
benefuexx

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