【问题标题】:Function Returning Whole Number, not Decimal函数返回整数,而不是小数
【发布时间】:2017-07-24 13:21:19
【问题描述】:

我正在尝试编写一个代码来查看一组数据并选择日期范围内的集合并找到它的平均值。问题是我的函数返回整数而不是小数。我试图将我的函数数据类型更改为单、双和长,但这些都没有奏效。日期列表在 A 列中,而我要平均的值在 B 列中。我的代码:

Function MONTHLYAVERAGE(OneDate As Date, TwoDate As Date) As Double

Dim TwoDate_Row As Long

Dim i, j As Integer
LookupColumn = "A"
Dim EndRange As Long

EndRange = Range("A1", Range("A1").End(xlDown)).Rows.Count


    For i = 1 To EndRange
        If Range(LookupColumn & i).Value = TwoDate Then TwoDate_Row = i
    Next i


    For j = TwoDate_Row To 1 Step -1
        If Range(LookupColumn & j).Value = OneDate Then OneDate_Row = j
    Next j

        Dim MyDateRange As Range

            LookupColumn2 = "B"

            Set MyDateRange = Range(LookupColumn2 & OneDate_Row & ":" & LookupColumn2 & TwoDate_Row)

        MONTHLYAVERAGE = Format(Application.WorksheetFunction.Average(MyDateRange), Standard)

End Function

【问题讨论】:

  • Format(Application.WorksheetFunction.Average(MyDateRange), Standard)- 什么是Standard
  • 这里有两件事可以请您创建一个消息框并提供以下行的结果 MONTHLYAVERAGE = Format(Application.WorksheetFunction.Average(MyDateRange), Standard),还将标准替换为“0.00”
  • 在声明所有变量后为我工作。"Standard" 返回84.1。标准的定义是:显示千位分隔符,小数点左边至少一位,小数点右边两位。
  • 你的意思是使用"Standard"(字符串文字)吗?

标签: vba excel average


【解决方案1】:

要重写您的代码,您可以使用FIND 来获取您想要的行号。

Public Function MonthlyAverage(StartDate As Date, EndDate As Date, Optional ColOffSet As Long = 1) As Double

    Dim rFirstCell As Range, rLastCell As Range

    With ThisWorkbook.Worksheets("Sheet1").Columns(1)
        'Find first instance of StartDate.
        Set rFirstCell = .Find(StartDate, , , , xlByRows, xlNext)
        If Not rFirstCell Is Nothing Then
            'Find last instance of EndDate.
            Set rLastCell = .Find(EndDate, , , , xlByRows, xlPrevious)
            'Both dates have been found, so we can calculate the average.
            If Not rLastCell Is Nothing Then
                MonthlyAverage = WorksheetFunction.Average(rFirstCell.Resize(rLastCell.Row - rFirstCell.Row + 1).Offset(, 1))
            End If
        End If
    End With

End Function

您可以将代码称为:

Sub Test()

    Dim TheAnswer As Double
    TheAnswer = MonthlyAverage(CDate("01/02/2017"), CDate("01/03/2017"))

    MsgBox TheAnswer

End Sub

如果您将TheAnswer 声明为双精度,则至少对我而言,它给出了84.1034482758621 的结果,如果我将其声明为长整数,则返回84

现在,另一种不使用 VBA 的方法:
如果您的日期在 A 列中,而您的数字在 B 列中。
在单元格E2 中输入所需的开始日期,在单元格E3 中输入所需的结束日期并使用以下公式:
=AVERAGE(INDEX($B:$B,MATCH($E$2,$A:$A,0)):INDEX($B:$B,MATCH($E$3,$A:$A,0)+COUNTIF($A:$A,$E$3)-1))

如果只有唯一日期,您可以删除 +COUNTIF($A:$A,$E$3)-1) 部分。

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    相关资源
    最近更新 更多