View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Jacob Skaria Jacob Skaria is offline
external usenet poster
 
Posts: 8,520
Default Best Practice - Cell and Range references in VBA?

When you are not sure about the last row of particular column then
lngLastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row

'When you are not sure about the last used column in a particular row
lngLastCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

If you are not at all sure about the range..the below will help
Set rngTemp = Activesheet.Usedrange


If you are looking at referencing; when you work with column numbers and row
numbers try

Range(Cells(r1,c1), Cells(r2,c2))
where r1,c1,r2,c2 are numbers

When you work with row numbers try Range("A1","J10") OR Range("A1:J10")
Range("A" & r1 & ":J" & r2)
Range("A" & r1 , "J" & r2)
where r1 and r2 are row numbers and A and J are column names or you can
replace those with string variables.

OR

Range(Cells(r1,"A"),Cells(r2,"J")) where r1 and r2 are row numbers and A and
J are column names or you can replace those with string variables.


If this post helps click Yes
---------------
Jacob Skaria


"DocBrown" wrote:

I have seen many methods to reference ranges and cells in VBA. Also, in a WS
various techniques are used to allow for insertion and deletions of cells and
columns, such as relative and absolute addressing.

When rows and columns are changed in a WS, As far as I can tell, those
adjustments are not made in the Macros.

My question is: What is the best practice for coding functions and macros so
that they don't break if the rows and columns are changed in the worksheet we
are referencing?

Thanks,
John