I have written this code but it doesnt seems to be working , Why?
Dim oRo As String
Dim nRo As String
Lastro = ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
oRo = "J2:O" & Lastro
nRo = "Q2:V" & Lastro
Range("C2:G" & Lastro).Select
With Range("C2:G" & Lastro)
.Range("C2:G" & Lastro).Formula = "=IF(oRo*nRo<0,ROUNDUP(oRo*1.3,-2),IF(ABS(oRo) <=ABS(nRo),nRo,ROUNDUP(oRo*1.3,-2)))"
End With
End Sub
Your best bet for maintainability is to embrace R1C1 notation when you write formulas to Excel from VBA. I still can't read R1C1, but I use it exclusively to write formulas from VBA. Here's how:
Let's say you want this formula in G2
So type that in G2, select G2, and open the Immediate Window (Ctrl+G in VBE). In the IW, type
That will give you all that you need. You don't have to be able to read it, you just have to be sure you typed the right formula (in A1 notation) in cell G2. Now you can have super simple code like
All I did was copy the R1C1 formula from the Immediate Window and paste it into the code.
You are hardcoding the phrases "oRo" and "nRo"
When you get to this line to write the formula, you are not writing out the values of oRo and nRo, so excel is expectin them to be defined within name manager.
If you want to write out the calculated values of oRo and nRo, you will have to alter the code slightly:
notice no
select
is required, and as you are only dealing with one range, nowith
is required either. I would also suggest you add inOption Explicit
to the top of your procedure to ensure all variables are declared and spelled correctly.