Reputation: 115
I'm new to VBA and could greatly use some help using the Autofill/Filldown functions.
I'm setting up a macro to incorporate a Vlookup formula in cells of the first empty column of a new worksheet.
This works well for the first cell, but I am having trouble in copying the formula down to all of the cells in spreadsheet (or at least to row 450), using the autofill/filldown functions, as I do not know how to do this without defining the range. I cannot define the range as it will vary each time..
ActiveSheet.Range("IV1").End(xlToLeft).Offset(, 1).Formula = "=VLOOKUP(B2,Plate.xlsm!$R$3:$S$10,2,FALSE)"
Please help!
Upvotes: 0
Views: 2087
Reputation: 19727
Or you can do it directly like this:
With ActiveSheet
Dim FirstEmpCol As Long, LastRow As Long
FirstEmpCol = .Cells(1, .Columns.Count).End(xlToLeft).Offset(0, 1).Column
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
.Range(.Cells(2, FirstEmpCol), .Cells(LastRow, FirstEmpCol).Formula = _
"=VLOOKUP(B2,Plate.xlsm!$R$3:$S$10,2,FALSE)"
End With
Upvotes: 1
Reputation: 6105
This should do what you are looking for. It will find the first blank column in Row 2, insert the formula there, then copy it down to the last row using column B to check for last used row (since that is the column the VLookUp
is looking at:
Sub TesterIt()
Dim LastRow As Long, StartCell As Range
Set StartCell = ActiveSheet.Cells(2, Columns.Count).End(xlToLeft).Offset(0, 1)
StartCell.Formula = "=VLOOKUP(B2,Plate.xlsm!$R$3:$S$10,2,FALSE)"
LastRow = Range("B" & Rows.Count).End(xlUp).Row
Range(StartCell, Cells(LastRow, StartCell.Column)).FillDown
End Sub
Upvotes: 0