Note: The following examples assumes the data range starts in Cell "A1" or Cell(1,1).
For Rows:
Set MyRng = Range("A1", Range("A65536").End(xlUp))Or Set MyRng = Range(Cells(1,1), Cells(65536,1).End(xlUp))
For Columns:
Set MyRng = Range("A1", Range("IV1").End(xlToLeft))Or Set MyRng = Range(Cells(1,1), Cells(1,256).End(xlToLeft))
I don't know why people hard code the last row/column values; the practice makes for code that can be difficult to edit/troubleshoot later on. Plus, it's not really backwards compatible. Sure the above examples work for Excel 2003 and earlier, but if you're working with Excel 2007 or later you potentially miss capturing a large amount of data. (1,048,576 Rows and 16,384 Columns are available in Excel 2007 and late).
To avoid hardcoding values, and making the code compatible with Excel 03 and later, I do this:
Dim lMaxRows as Long Dim lMaxCols as Long lMaxRows = Rows.Count lMaxCols = Columns.Count
So defining your range now looks like this:
For Rows:
Set MyRng = Range("A1", Range("A" & lMaxRows).End(xlUp))Or Set MyRng = Range(Cells(1,1), Cells(lMaxRows,1).End(xlUp))
For Columns:
Set MyRng = Range(Cells(1,1), Cells(1,lMaxCols).End(xlToLeft))
Non-sequitur: Some people don't like using the "Cells" property to reference ranges or cells, but I say poo on that (admittedly it does make reading code more difficult). Using the Cells property makes coding loops easier. So there.
Takeaway: Avoid hardcoding - it makes debugging more difficult.
No comments:
Post a Comment