通过迭代器作为日期

时间:2019-06-20 06:42:33

标签: excel vba if-statement

嗨(请原谅我不是编码器的错误格式和约定)

我有一个VBA函数,用于在给定日期和值表的情况下计算时间加权平均值。问题是我无法通过excel函数之一传递迭代器。

问题出现在以下行:

totalWeighting = totalWeighting + Cells(Application.Match(start_date, dateRange, 1), userCodeColumn)

在使用start_date时,该功能可以正常工作(请注意,我在Dim variables上还有很多其他代码已被排除)。但是,将start_date替换为“ d”时,它将返回#value

Function TimeWeightedAverage(start_date As Date, end_date As Date, user_code) As Double

Dim d As Date
Dim totalWeighting As Double
Dim userCodeColumn As Integer
Dim dateRange As Range
Dim denominator As Integer
Dim startRow As Integer

If Mid(user_code, 3, 1) = 2 Then
    Set dateRange = ActiveSheet.Range("A:A")
    Else
        Set dateRange = ActiveSheet.Range("H:H")
End If

totalWeighting = 0
denominator = WorksheetFunction.NetworkDays(start_date, end_date)
Let userCodeColumn = user_code.Column
Let startRow = Application.Match(start_date, dateRange, 1)

For d = start_date To end_date
    If WorksheetFunction.Weekday(d, 11) < 6 Then
        totalWeighting = totalWeighting + Cells(Application.Match(d, dateRange, 1), userCodeColumn)
    End If
Next



TimeWeightedAverage = totalWeighting / denominator

任何想法都将不胜感激。

数据:

Data

1 个答案:

答案 0 :(得分:0)

好吧,我想我已经解决了你的问题。

首先,像您所使用的那样的循环适用于整数/长/单/双...不是日期,因此您不能使用d作为日期,因为它不是。

另一方面,您声明了一个startrow,它没有像denominator那样使用,它正在计算两个日期之间的工作日。取而代之的是,计算两个日期之间的所有日期,然后循环遍历所有日期,一次增加1天到startdate,然后将该天赋给Date变量,则您的If语句将处理是否是工作日。

Option Explicit
Function TimeWeightedAverage(start_date As Date, end_date As Date, user_code As Range) As Double

    Dim d As Long
    Dim userCodeColumn As Long
    Dim dateRange As Range
    Dim denominator As Long
    Dim CheckDate As Date

    If Mid(user_code, 3, 1) = 2 Then
        Set dateRange = ActiveSheet.Range("A:A")
    Else
        Set dateRange = ActiveSheet.Range("H:H")
    End If

    denominator = DateDiff("d", start_date, end_date)
    Let userCodeColumn = user_code.Column

    For d = 1 To denominator
        If d = 1 Then
            CheckDate = start_date
        Else
            CheckDate = start_date + d
        End If
        If WorksheetFunction.Weekday(CheckDate, 11) < 6 Then
            TimeWeightedAverage = TimeWeightedAverage + ActiveSheet.Cells(Application.Match(CheckDate, dateRange, 1), userCodeColumn)
        End If
    Next

End Function