Reputation: 3
I would like to limit all of the formulas in a selected range of cells with an additional if statement.
Is it doable with the use of the VBA?
Let's say: cell A1 contains =sum(B1;C1) but it can be any formula that a selected cell contains after applying macro updated formula would be =if(D100>0;sum(B1;C1);0)
=if(D100>0;any formula in a cell ;0)
Upvotes: 0
Views: 152
Reputation: 7627
You can achieve this by using code like this:
Sub ModifyFormulas()
Dim cl As Range, formulas_cells As Range
Const template = "=if(D100>0,#,0)" '# will be replaced by old formula without '='
On Error Resume Next ' handle an error if there are no formulas in the range
Set formulas_cells = Range("A1:A10").SpecialCells(xlCellTypeFormulas)
On Error GoTo 0
If Not formulas_cells Is Nothing Then
For Each cl In formulas_cells
cl.Formula = Replace(template, "#", Mid(cl.Formula, 2))
Next
End If
End Sub
Upvotes: 1
Reputation: 8375
Without vba, I use the following method:
edit / replace the "=" with "xyxy" - this stops excel recalculating
then edit / replace "sum" with "if(D100>0;sum"
then edit / replace ")" with ");0)"
lastly replace "xyxy" with "="
and then it all works, done this often with my sheets when I have to change some calculations...
Upvotes: 0