简体   繁体   中英

Autofill/FillDown Formulas with Changing Range

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM