首页 > 解决方案 > (EXCEL-VBA)尝试将日期作为标准传递给 MedianIFS UDF,但仅解析月份(通过 MID 函数)以获得标准阈值

问题描述

我正在使用 MEDIANIFS UDF(由 Dan Wagner 编写)按用户名和日期(<= 用户指定日期和 > 12 个月前的日期)过滤辐射徽章读数。日期通过我自己的子例程中的变量传递给 UDF,但是当定义 varThreshold 变量时,它仅显示为月份(IE:而不是 2018 年 7 月 28 日,varThreshold = 7)。这使得后面的逻辑参数返回为假。varThreshold 由 Mid 函数解析的数据定义。一旦碰到“/”分隔符,它似乎停止解析字符串。下面的代码示例。

我调用 MEDIANIFS UDF 的子程序片段:

'-------------Calculate current and past 12 month dates and assign to variables
    mth = Month(DateValue("01 " & Range("D2") & " 2019"))
    yr = Range("E2")
    currDate = DateSerial(yr, mth, 28)
    pastDate1 = DateAdd("M", -12, currDate)
    pastDate = DateAdd("D", -27, pastDate1)
'-------------Loop to apply past 12 month calculation to each individual Doctor
For i = mdX To mdY
    EPmdNme = Range("A" & i)
    Range("B" & i) = MEDIANIFS(LdeRng, NameRng, EPmdNme, DateRng, "<=" & currDate, DateRng, ">" & pastDate)
    Range("B" & i).NumberFormat = "0.0"
Next I

这里 currDate = 7/28/18

MEDIANIFS UDF 的相关部分:

        'Loop through all the range / criteria pairs
    For lngCriteriaIdx = LBound(range_and_criteria_pairs) To UBound(range_and_criteria_pairs) Step 2
        'Identify the threshold and the operator for use in the criteria phase
        Select Case Left(range_and_criteria_pairs(lngCriteriaIdx + 1), 2)
            Case Is = "<="
                strOperator = "<="
                varThreshold = Val(Mid(range_and_criteria_pairs(lngCriteriaIdx + 1), 3))
            Case Is = ">="
                strOperator = ">="
                varThreshold = Val(Mid(range_and_criteria_pairs(lngCriteriaIdx + 1), 3))

这使得 varThreshold = 7

稍后在 MEDIANIFS UDF 中,将 varThreshold 与“Data”变量进行比较。在这种情况下,数据 = #1/1/18#:

            'Criteria phase: check each cell in the passed-in ParamArray against the threshold
        With range_and_criteria_pairs(lngCriteriaIdx)

            Data = .Cells(lngMedianRowIdx, 1).Value
            If VarType(Data) = 7 Then
                Data = CDate(.Cells(lngMedianRowIdx, 1).Value)
            ElseIf VarType(Data) = 8 Then
                Data = UCase(.Cells(lngMedianRowIdx, 1).Value)
            Else
                Data = .Cells(lngMedianRowIdx, 1).Value
            End If

                'Check the operator (">=", "<=", "<", ">", "<>", and "=") against the cell
            Select Case strOperator
                Case Is = "<=" '<~ check if cell is less than or equal to the threshold
                    If Data <= varThreshold Then
                        blnAllMatched = True
                    Else
                        blnAllMatched = False
                    End If

显然,这会返回错误并否定整个 UDF。

我怎样才能让 varThreshold 等于 currDate 所以 varThreshold = 7/28/18 以便 Data <= varThreshold (#1/1/18# <= 7/28/18) 所以我得到一个“真实”的结果?

varThreshold 也用于过滤名称,因此必须将其定义为变体。

标签: excelvbauser-defined-functionsdate-format

解决方案


推荐阅读