Macro not working. Need last used row in spreadsheet.

I've been using this macro to fix the leading zero on the zip codes stored in column M.  Now that I've needed to move to Excel '07 due to having files that no longer fit in the older version of Excel I need to update this macro to use the ACTUAL last row instead of a hard-coded number (65536).  However, I've tried several different methods to find the last row and the macro refuses to work.

Among other things I've attempted:
Dim LR as long
LR = ActiveSheet.UsedRange.Rows.Count
set rg = Range(Cells(2, col), Cells(LR, col).end(xlUp))


Dim LR as long
LR = Cells.SpecialCells(xlCellTypeLastCell).Row
set rg = Range(Cells(2, col), Cells(LR, col).end(xlUp))


set rg = Range(Cells(2, col), Cells(ActiveSheet.UsedRange.Rows.Count, col).end(xlUp))


set rg = Range(Cells(2, col), Cells(Cells.SpecialCells(xlCellTypeLastCell).Row, col).end(xlUp))

Nothing seems to work aside from typing in a hard-coded number.
Sub ZipCoder3()
Dim rg As Range
Dim col As Long
Application.ScreenUpdating = False
col = Columns("M").Column
Columns(col + 1).Insert
Set rg = Range(Cells(2, col), Cells(65536, col).End(xlUp))
rg.NumberFormat = "00000"
rg.Offset(0, 1).FormulaR1C1 = "=LEFT(RC[-1],5)"
rg.Formula = rg.Offset(0, 1).Value
rg.Offset(0, 1).EntireColumn.Delete
Application.ScreenUpdating = True
End Sub

Open in new window

Who is Participating?
StephenJRConnect With a Mentor Commented:
Try substituting Rows.Count for 65536 in line 7.

Try this format:

With Sheets("Sheet1")
    Set rg = .Range(.Cells(2, "M"), .Cells(.rows.count, "M").End(xlUp))
End With

Note the leading periods. Also it's important to spefify the worksheet on which this is to work, otherwise it will apply to whatever worksheet you are currently on. Change With Sheets("Sheet1") to whatever is correct for your workbook.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.