我想要一个计算给定范围之和的公式。
说我在单元格1,5
中有A1
。我想要一个公式来计算1+2+3+4+5
。
也许以更高级的方式,我想输入1,5;6,3;1,4;...
并计算(1+2+3+4+5)+(6+5+4+3)+(1+2+3+4)
。
不会有任何负数。
这在Excel中是否可行?对于范围6,3
,最简单的是获得较低的数字并计算最多6个。
答案 0 :(得分:3)
这里有一个user-defined function可以满足您的需求。它也适用于否定。没有错误检查,例如,单元格中的字母,分号之间不止一个逗号(第一个将产生#VALUE错误)。
在工作簿或插件的模块中输入此功能:
Function AddSubstringProgressions(CellContent As String)
Dim Progressions As Variant
Dim Progression As Variant
Dim i As Long, j As Long
Dim Total As Long
Dim Stepwise As Long
Progressions = Split(CellContent, ";")
For i = LBound(Progressions) To UBound(Progressions)
Progression = Split(Progressions(i), ",")
If Val(Progression(LBound(Progression))) > Val(Progression(UBound(Progression))) Then
Stepwise = -1
Else
Stepwise = 1
End If
For j = Progression(LBound(Progression)) To Progression(UBound(Progression)) Step Stepwise
Total = Total + j
Next j
Next i
AddSubstringProgressions = Total
End Function
这样称呼:
答案 1 :(得分:1)
对于工作表函数方法,您可以尝试以下方法之一:
基本情况例如A1 = 1,5
或6,3
=SUMPRODUCT(ROW(INDIRECT(SUBSTITUTE(A1,",",":"))))
一般情况例如A1 = 1,5;6,3;1,4
。
定义名称A =EVALUATE("{"&A1&"}")
,然后输入:
=SUMPRODUCT(ABS(MMULT(A^2,{1;-1}))/2+A)/2
更新。基于上述方法的简短VBA udf ...
Function SumSeries(Val As String)
SumSeries = Evaluate("SUM(ABS(MMULT({" & Val & "}^2,{1;-1}))/2+{" & Val & "})/2")
End Function
答案 2 :(得分:0)
以下是我的想法:
Sub addRange()
Dim cell As Range
Dim count As Integer
count = Application.WorksheetFunction.CountA(Range("A:A"))
Dim i As Integer
i = 1
Do While i <= count
Dim low As Integer
Dim high As Integer
low = Mid(Range("A" & i), 1, Application.WorksheetFunction.Search(",", Range("A" & i)) - 1)
high = Mid(Range("A" & i), Application.WorksheetFunction.Search(",", Range("A" & i)) + 1, Len(Range("A" & i)))
If (low > high) Then
Dim copy As Integer
copy = low
low = high
high = copy
End If
Range("B" & i) = adder(low, high)
i = i + 1
Loop
End Sub
Function adder(low As Integer, high As Integer) As Integer
Dim sum As Integer
sum = 0
Do While low <= high
sum = sum + low
low = low + 1
Loop
adder = sum
End Function
这假设您在单元格A1:An中包含2,5
,6,4
,1,8
等值。它不适用于像2,5;6,4
这样的值,因为你描述的是更高级的函数,但它可以完成基本函数的工作。