Chose Range of rows using two variables

cogswel__cogs

Board Regular
Joined
Jan 3, 2018
Messages
180
I want to write in vba code to select range of rows for example.

X = 5
y = 9

rows(x:y).select

How would I write it?
I've tried

I have tried

rows(x & ":" & Y).select

But it does not work.

All help is greatly apprciated.
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
Works just fine for me:
VBA Code:
Sub MyTest()

    Dim x As Long, y As Long
    
    x = 5
    y = 9
    
    Rows(x & ":" & y).Select
    
End Sub
 
Upvote 0
Hello cogswel,

You might try this

To select a range of rows in VBA using variables for the start and end rows, you need to use the Rows property of the active worksheet and convert the range to a string. Here's the correct way to write it:



Dim x As Long
Dim y As Long

x = 5
y = 9

Rows(x & ":" & y).Select

The issue with your attempt was likely the capitalization of the variable Y. In VBA, variable names are case-insensitive, so Y and y refer to the same variable. It's a good practice to be consistent with your capitalization.

Here's a breakdown of why this works:

  1. x & ":" & y creates a string like "5:9"
  2. Rows("5:9") is equivalent to selecting rows 5 through 9
  3. The Select method is then applied to this range
If you want to make your code more robust, you could also use the following alternative:



Range(Rows(x), Rows(y)).Select

This approach uses the Range object to select from row x to row y, which can be slightly more flexible in some situations.



Hope this helps,

Plettieri
 
Upvote 0
Solution

Forum statistics

Threads
1,223,904
Messages
6,175,295
Members
452,632
Latest member
jladair

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