代码之家  ›  专栏  ›  技术社区  ›  BruceWayne

UDF总和不返回小数位数,仅返回整数

  •  0
  • BruceWayne  · 技术社区  · 11 年前

    我有一个UDF,它将上面的单元格相加,直到达到一个格式化为百分比的单元格。求和公式有效,我可以返回一个数字。。。然而,它似乎在四舍五入/截断答案。

    代码:

     Function sumAbove(cel As Range) As Variant
    Dim firstCell As Integer
    Dim i As Integer
    
    i = 1000
    
    With cel
        For i = 1 To 1000
            If cel.Offset(-i, 0).NumberFormat = "0.00%" Then
                firstCell = cel.Offset(-i, 0).Row
                Exit For
            End If
        Next i
    End With
    
    sumAbove = WorksheetFunction.Sum(Range(Cells(firstCell, cel.Column), Cells(cel.Row, cel.Column)))
    
    End Function
    

    我试过了 Function sumAbove(cel as Range) Integer Double ,无结果。当我试图将其设置为 Float ,我收到一个错误“用户定义的类型未定义”。

    使用此列表:

    25.00%
    5
    5
    5
    5
    5.5
    

    上面的代码将正确使用单元格5+5+5+5.5——然而,它错误地得到了总和。如果我将UDF设置为整数,它的值仅为25。如果将UDF更改为Double,它将返回25.75(??),等

    如何使其返回25.50?感谢您的任何提示或建议!

    1 回复  |  直到 8 年前
        1
  •  3
  •   SierraOscar    11 年前
    firstCell = cel.Offset(-i, 0).Row
    

    这包括 SUM 作用
    (25%=0.25,这就是为什么你得到了.75)

    请改用以下内容:

    Function SumAbove(cell As Range) As Double
    Dim firstCell As Long
    Dim i As Integer
    
    firstCell = cell.Row
    
    While Not cell.Offset((cell.Row - firstCell) * -1, 0).NumberFormat = "0.00%"
        firstCell = firstCell - 1
    Wend
    SumAbove = WorksheetFunction.Sum(Range(Cells(firstCell + 1, cell.Column), cell))
    
    End Function
    
    推荐文章