我有一张这样的 Excel 表,有没有办法在 VBA 中使用 C6 获取 C8 中的值?
答案1
非 VBA 方法:
根据具体情况命名范围
因此,C2 将是x
,C3 将是y
并且...
要快速完成此操作:
突出显示 B2:C4
在公式选项卡上单击
Create from Selection
选择
Left
然后点击确定
这将分别将 C 列中突出显示的单元格命名为 x、y、z。
那么 C6 中的公式将是:
=x*y*1000/z
然后在 C8 中:
=FORMULATEXT(C6)
如果这不起作用那么以下 UDF 将会执行您想要的操作:
Function Foo(rng As Range) As String
Dim MathArr()
'Add to this array as needed to find all the math functions
MathArr = Array("*", "-", "+", "/", "(", ")")
Dim strArr() As String
Dim temp As String
Dim strFormula As String
Dim i As Long
'Hold two versions of the formula, one manipulate and the other to use.
strFormula = rng.Formula
temp = rng.Formula
'Replace all math functions with space
For i = LBound(MathArr) To UBound(MathArr)
strFormula = Replace(strFormula, MathArr(i), " ")
Next i
'Split on the space
strArr = Split(strFormula)
'iterate and test each part if range
For i = LBound(strArr) To UBound(strArr)
If test1(strArr(i)) Then
'If range then we repace that with the value to the right of that range
temp = Replace(temp, strArr(i), Range(strArr(i)).Offset(, -1).Value)
End If
Next i
'Return text
Foo = "=" & temp
End Function
Function test1(reference As String) As Boolean
Dim v As Range
' if the string is not a valid range it will throw and error
On Error Resume Next
Set v = Range(reference) 'try to use referenced range, is address valid?
If Err.Number > 0 Then
Exit Function 'return false
End If
On Error GoTo 0
test1 = True
End Function
由于没有命名范围,因此 C6 中的公式是=C2*C3*1000/C4
,我将其放在 C8 中:
=Foo(C6)