Thursday, November 11, 2010

How do I select a range in VB for Excel?

I need to select a range, that changes every time I run the program.How do I select a range in VB for Excel?
There are many ways that a Range could be Selected. But having the code know which area to select based upon changes is another matter. There must be some criteria to use for the selection process.



Here are just some of the ways to select ranges using VBA code within MS-Excel:



Range(';A1:D4';).Select

Range(Cells(1, ';A';), Cells(4, ';D';)).Select

Range(Cells(1, 1), Cells(4, 4)).Select

Range(';A1';, [A1].Offset(3, 3)).Select

[A1:D4].Select

Rows(ActiveSheet.UsedRange.Row).Select

Activesheet.UsedRange.Select

Range(';A1';, Range(';A'; %26amp; Rows.Count).End(xlUp)).Select





Dim rng As Range

Set rng = ActiveWindow.RangeSelection

Set rng = Worksheets(';Sheet1';).Range(';B:B';)

Set rng = ActiveCell.CurrentRegion





Selection.SpecialCells( xlCellTypeLastCell ).Select

Rows(';2:5000';).Select





If you want to see explanations and examples of some of the above, just paste them into a Module and select a specific word. Then use the F1 key to get Help to show you what that is for and means.



.How do I select a range in VB for Excel?
it depends on what you mean by change and how it changes. You can set variables and insert them into the selected range

ex

TopRng = Formula or statement to reevaluate each time it is run

BtmRng = Formula or statement to reevaluate each time it is run

Sheets(';Sheet1';).Range(';A'; %26amp; TopRng %26amp; ';:B'; %26amp; BtmRng ).select
There are several methods....



'These methods select cells B2 to D10...

Range(';B2:D10';).Select

[B2:D10].Select

Range(Cells(2, 2), Cells(10, 4)).Select

Range(Cells(2, ';B';), Cells(10, ';D';)).Select

Range(';B2';, [B2].Offset(8, 2)).Select





'Select the used range of cells on a sheet

Activesheet.UsedRange.Select



'Select 1st used row

Rows(ActiveSheet.UsedRange.Row).Select



'Select last used Row

Rows(Activesheet.UsedRange.Row + Activesheet.UsedRange.Rows.Count -1).Select



'Select A1 to the last used cell in column A

Range(';A1';, Range(';A'; %26amp; Rows.Count).End(xlUp)).Select





If you are calculating the rows and columns that you want to select where r1 is the 1st row number, r2 is the last row number, c1 is the 1st column number, and c2 is the last column number...

Range(Cells(r1, c1), Cells(r2, c2)).Select





Here's a site with a few more examples



Finding the Last Cell in a Range

http://www.ozgrid.com/VBA/ExcelRanges.ht鈥?/a>
You can assign the following code to the macro you are running :



...

Range(';A1:C3';).select

...

...



etc

No comments:

Post a Comment