
求EXCEL VBA 程序:在EXCEL的A1到J1里分别有数据1,3,4,4,6,9,7,5,2,3。在A2到J2里分别有数据1,2
,5,6,7,8,4,3,6,8。现要对A2到J2里的数据从最大的开始进行SUM运算,直到SUM大于25时结束SUM运算,要求输出参与SUM运算的数据对应的上面的数值(即...
,5,6,7,8,4,3,6,8。现要对A2到J2里的数据从最大的开始进行SUM运算,直到SUM大于25时结束SUM运算,要求输出参与SUM运算的数据对应的上面的数值(即A1到J1中的数据)。
只要把下面的VBA改下即可:
Public Function iSumLarge(iRes, iRng As Range)
'VBA函数,iRng内,从大到小开始sum,到iRes为止,取得这些数据
Application.Volatile
If iRng.Cells.Count < 1 Then iSumLarge = "#iRng": Exit Function
Dim i&, iLgVal, tmp, s$, a
For i = 1 To iRng.Cells.Count
iLgVal = Application.WorksheetFunction.Large(iRng, i)
tmp = tmp + iLgVal
s = s & iLgVal & ","
If tmp > iRes Then Exit For
Next
iSumLarge = IIf(tmp < iRes, "<=" & iRes, Left(s, Len(s) - 1))
End Function 展开
只要把下面的VBA改下即可:
Public Function iSumLarge(iRes, iRng As Range)
'VBA函数,iRng内,从大到小开始sum,到iRes为止,取得这些数据
Application.Volatile
If iRng.Cells.Count < 1 Then iSumLarge = "#iRng": Exit Function
Dim i&, iLgVal, tmp, s$, a
For i = 1 To iRng.Cells.Count
iLgVal = Application.WorksheetFunction.Large(iRng, i)
tmp = tmp + iLgVal
s = s & iLgVal & ","
If tmp > iRes Then Exit For
Next
iSumLarge = IIf(tmp < iRes, "<=" & iRes, Left(s, Len(s) - 1))
End Function 展开
1个回答
展开全部
程序没有问题,可以输出S
调用格式类似:Call iSumLarge(25, Range("a2:j2"))
调用格式类似:Call iSumLarge(25, Range("a2:j2"))
追问
你好,我要返回的是进行SUM运算的上一行的数据,而不是进行SUM运算的数据
追答
一下代码适用数据最大值是唯一的情况,如果递减最大值有重复项,则返回最左边项的上一行单元格
Public Function iSumLarge(iRes, iRng As Range)
'VBA函数,iRng内,从大到小开始sum,到iRes为止,取得这些数据
Application.Volatile
If iRng.Cells.Count iRes Then Exit For
Next
iSumLarge = IIf(tmp < iRes, "<=" & iRes, Left(s, Len(s) - 1))
End Function
Sub test()
Call iSumLarge(25, Range("a2:j2"))
End Sub
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询