Using an integer to call next values

BritsBlitz

New Member
Joined
Jan 10, 2014
Messages
18
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?
 

Jerry Sullivan

MrExcel MVP
Joined
Mar 18, 2010
Messages
8,787
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.
 

Forum statistics

Threads
1,082,359
Messages
5,364,916
Members
400,815
Latest member
Joaquin Phoenix

Some videos you may like

This Week's Hot Topics

  • populate from drop list with multiple tables
    Hi All, i have a drop list that displays data, what i want is when i select one of those from the list to populate text from different tables on...
  • Find list of words from sheet2 in sheet1 before a comma and extract text vba
    Hi Friends, Trying to find the solution on my task. But did not find suitable one to the need. Here is my query and sample file with details...
  • Dynamic Formula entry - VBA code sought
    Hello, really hope one of you experts can help with this - i've spent hours on this and getting no-where. .I have a set of data (more rows than...
  • Listbox Header
    Have a named range called "AccidentsHeader" Within my code I have: [CODE]Private Sub CommandButton1_Click() ListBox1.RowSource =...
  • Complex Heat Map using conditional formatting
    Good day excel world. I have a concern. Below link have a list of countries that carries each country unique data. [URL...
  • Conditional formatting
    Hi good morning, hope you can help me please, I have cells P4:P54 and if this cell is equal to 1 then i want row O to say "Fully Utilised" and to...
Top