宏通用公式

时间:2013-09-22 17:52:24

标签: excel vba excel-vba

我有一张包含四列(A-D)的Excel表格,如下所示:

1   XYZ     100     800
2   XYZ     250     820
3   XYZ     500    1100
4   XYZ   4,000    1200

我想计算E列值如下:

E1 =(D1-D1)* C1
E2 =(D2-D1)* C1
E3 =(D3-D1)* C1 +(D3-D2)* C2
E4 =(D4-D1)* C1 +(D4-D2)* C2 +(D4-D3)* C3

如果还有其他行

,依此类推

预期结果:E1 = 0,E2 = 2000,E3 = 100000,E4 = 185000

是否有可能推广这个公式?任何帮助都非常感谢。

2 个答案:

答案 0 :(得分:2)

您无法在单元格中推广此公式,因为公式需要增长。此外,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

答案 1 :(得分:0)

很晚,但为什么你不能使用它 .. E4 = D4 * SUM(C $ 1:C3)-SUMPRODUCT(C $ 1:C3,D $ 1:D3) .. 代替 E4 =(D4-D1)* C1 +(D4-D2)* C2 +(D4-D3)* C3

为了防止性能下降,如果可以使用临时列,您可以创建列来存储C和C * D的部分和。