Search code examples
excelvba

Change formula to a function that evaluates the starting formula


I want a script that for every cell in a selected range, changes the formula to a function that evaluates what the starting formula is numerically equal to.

It seems .formula should work, because the object I want to get the formula for is a cell.

enter image description here

Sub Functions()
End Sub

Function GetFormula(Target As Range) As String
    GetFormula = Target.Formula
End Function
    
Function Eval(Ref As String)
    Application.Volatile
    Eval = Evaluate(Ref)
End Function

Sub FixFormat(gyaat As Ranges)
    For Each c In Range(gyaat).Cells
        c.Formula = Eval(GetFormula(c.Adress))
    Next
End Sub

Sub bruh()
    
    If TypeName(Selection) = "Range" Then
        Dim myRange As Range
        Set myRange = Selection
        Dim myCells As Object
        
    Else
        MsgBox "Please select a Range", vbInformation
    End If
    
    For Each myCells In myRange
        myCells.Formula = Eval(GetFormula(myCells.Adress))
    Next
    
End Sub

If completely wrong, what should I do instead?

I'm thinking the function in any myCells cell might contain references to other cells, but I could make a separate macro for that.

I tried a custom function, but functions are for setting the value of the cell that uses them, so I don't think where you select cells and the value of the selected cells gets changed is a thing.


Solution

  • Your GetFormula function expects a range.

    Function GetFormula(Target As Range) As String
        GetFormula = Target.Formula
    End Function
    

    But when you call it, you pass an address/a string:

    c.Formula = Eval(GetFormula(c.Adress))
    

    So, change this line to:

    c.Formula = Eval(GetFormula(c))