Add Formula To Cell With VBA

Excel Insert Formula Into Cell With Macro 


           With macro , formulas inserting  are fast especially to multiple cells  .

Sheets("DATA").Range("I2").AutoFill Destination:=Range("I2:I" & lastrow), Type:=xlFillDefault

Issues to be considered :
✔️ The extra quotes  must be used .
     Example : "= IF(D12<=0,"”valid”,F2*H2)"

✔️ The comma must be used instead of semicolon.
     Example : "= IF(F2<=0, H2,F2*H2)" 

✔️ When used into the worksheet : "= IF(F2<=0; H2;F2*H2)"   


Excel insert formulas to cell with macro


All codes of our macro :
Sub carp()
Dim lastrow As Long
lastrow = Sheets("DATA").Cells(Rows.Count, "H").End(xlUp).Row
Sheets("DATA").Range("I:I").Locked = False
Sheets("DATA").Range("I2").Select

ActiveCell.Formula = "= IF(F2<=0, H2,F2*H2)"
Sheets("DATA").Range("I2").AutoFill Destination:=Range("I2:I" & lastrow), Type:=xlFillDefault

Sheets("DATA").Range("I:I").Locked = True
End Sub


2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi, what if i want to protect columns "I" when the formulas is pasted. Is it possible?
    can you provide the example to download?
    Thanks

    ReplyDelete