函数返回整数,而不是十进制

时间:2017-07-24 13:21:20

标签: vba excel-vba average excel

我正在尝试编写一个查看一组数据的代码,并在日期范围内选择该集合并找到它的平均值。问题是我的函数返回整数而不是小数。我试图将我的函数数据类型更改为single,double和long,但这些都没有奏效。日期列表在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

1 个答案:

答案 0 :(得分:2)

要重写代码,您可以使用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的结果,如果我将其声明为long,则会返回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)部分。