您将无法在单元格中推广此公式,因为公式需要增长。此外,Excel 单元格中的公式有字符限制(请参阅下面的 @pnuts 评论),因此您无法可靠地使用 VBA 来“构建”公式,因为在一定数量的行之后,您将超过该阈值。虽然您的用例可能不会遇到此限制,但在这种情况下,我更喜欢 UDF 的简单性,而不是“构建”长公式字符串的 VBA 子例程。
您可以编写一个自定义函数,通过迭代范围来计算值。这适用于您的示例数据。将代码放在标准代码模块中。
Public Function GetValue(ByVal clStart As Range, ByVal clEnd As Range) As Variant
'Pass only the cell address for the first cell ("D1") and the last cell ("D4")
Dim rng As Range
Dim r As Range
Dim i As Long
Dim myVal As Double
Application.Volatile
If Not clStart.Column = clEnd.Column Then
'These cells should be in the same column, if not
' display an error
myVal = CVErr(2023)
GoTo EarlyExit
End If
Set rng = Range(clStart.Address, clEnd.Address)
For i = 1 To rng.Rows.Count - 1
Set r = rng.Cells(i)
myVal = myVal + _
((clEnd.Value - r.Value) * r.Offset(0, -1).Value)
Next
EarlyExit:
GetValue = myVal
End Function