Is there a way to convert a cell-based formula so the cells in the formula are substituted to their actual values? Without auto-completing?
Here's an example, lets just say the formula is:
=A1+A2+B6
And...
A1=2, A2=5 and B6=21.
How can I turn my formula from this..
=A1+A2+B6
...to this...
=2+5+21
...without doing it manually? I believe there is a way.
Thank you.
This should work for simple situations where all of the formula references are on the same sheet. I use the DirectPrecedents
range, but that limits you to precedent cells on the same sheet.
In my example I have, this in Sheet1
| A |
--+---------------------------------------------+
1 | 2 |
2 | 4 |
3 | 6 |
4 | =Sheet1!A3+(A1^Sheet1!A1)+Sheet1!A2/(A3+A2) |
5 | =SUM(A1,A2,A3)/COUNT(A1,A2,A3) |
Note the mix of cell references that include a cell with a named sheet prefix.
And I use this VBA code:
Option Explicit
Sub Test()
PrintResolvedFormula Range("A4")
PrintResolvedFormula Range("A5")
End Sub
Sub PrintResolvedFormula(rng As Range)
If rng.HasFormula Then
Dim formula As String
formula = rng.FormulaR1C1
Dim cel As Range
For Each cel In rng.DirectPrecedents.Cells
formula = Replace(formula, cel.Worksheet.Name & "!", vbNullString)
formula = Replace(formula, cel.Address(False, False, xlR1C1, False, rng), cel.Text)
Next cel
Debug.Print formula
Else
Debug.Print rng.Value
End If
End Sub
And get this output:
=6+(2^2)+4/(6+4)
=SUM(2,4,6)/COUNT(2,4,6)
Note that is resolves the cell references to values, but it does not resolve the functions to values. To resolve the individual functions you'd to break out the function string and use Application.Evaluate
.
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.