I know you’ve answered similar topics which I have tried to duplicate, but I am a novice and apparently need the answer spelled out for me! I am trying to apply autofill code to a MAX formula column within a Macro, so that it will autofill to different row counts each time.

```
Range("AC2").Select
ActiveCell.FormulaR1C1 = "=MAX(RC[-2],RC[-1])"
Selection.AutoFill Destination:=Range("AC2:AC285")
Range("AC2:AC285").Select
```

Thank you!

It is only important to fill the formula down to the last value within the columns referenced within the formula.

```
dim lr as long
with worksheets("sheet1")
lr = application.max(.cells(.rows.count, "AA").end(xlup).row, _
.cells(.rows.count, "AB").end(xlup).row)
.Range("AC2:AC" & lr).FormulaR1C1 = "=MAX(RC[-2],RC[-1])"
end with
```

### Answer：

Assuming there are no blanks between the first and last row in column AC this will work and you don’t even need `AutoFill`

```
With Range(Range("AC2"),Range("AC2").End(xlDown))
.FormulaR1C1 = "=MAX(RC[-2],RC[-1])"
End With
```

This works specifically becuase you are using R1C1 notation which can be applied across all cells.

If there may be blanks, you can find last row like below and fill the formulas the same way:

```
Dim lastRow as Long
lastRow = Range("AC" & Rows.Count).End(xlUp).Row
With Range("AC2:AC" & lastRow)
.FormulaR1C1 = "=MAX(RC[-2],RC[-1])"
End With
```

### Answer：

So you have two main tasks:

- how to define last row in a given column;
- how to define range, based on a row and column;

This is the answer both:

```
Option Explicit
Sub TestMe()
Dim currLastRow As Long
currLastRow = lastRow(columnToCheck:=4)
With Worksheets(1)
.Range("D1").FormulaR1C1 = "=MAX(RC[-2],RC[-1])"
.Range("D1").AutoFill Destination:=.Range(.Cells(1, "D"), .Cells(currLastRow, "D"))
End With
End Sub
Function lastRow(Optional wsName As String, Optional columnToCheck As Long = 1) As Long
Dim ws As Worksheet
If wsName = vbNullString Then
Set ws = ActiveSheet
Else
Set ws = Worksheets(wsName)
End If
lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row
End Function
```

The `lastRow`

function gives the last row per column. In your case, you want column `D`

, e.g. the 4. column.

Tags: excelexcel, function