Excel VBA - select a dynamic cell range Excel VBA - select a dynamic cell range vba vba

Excel VBA - select a dynamic cell range


If you want to select a variable range containing all headers cells:

Dim sht as WorkSheetSet sht = This Workbook.Sheets("Data")'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUSTsht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select

...as long as there's no other content on that row.

EDIT: updated to stress that when using Range(Cells(...), Cells(...)) it's good practice to qualify both Range and Cells with a worksheet reference.


sub selectVar ()    dim x,y as integer    let srange = "A" & x & ":" & "m" & y    range(srange).selectend sub

I think this is the simplest way.


So it depends on how you want to pick the incrementer, but this should work:

Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)

If you want the beginning to be dynamic as well, you can try this:

Sub SelectCols()    Dim Col1 As Integer    Dim Col2 As Integer    Col1 = 2    Col2 = 4    Range(Cells(1, Col1), Cells(1, Col2)).SelectEnd Sub