Excel VBA UDF Count Ifs with data conversion

Excel VBA UDF Count Ifs with data conversion

我正在尝试使用 Countifs 编写 UDF。我希望用户能够 select 条件 1(保留为 X1)和月份(保留为 month_X)。查找 table 中的月份是数字,所以我希望函数将月份名称转换为月份编号。

这行得通 - 但是否有更好的方法来转换数据? IE。更少的代码行?

Function CountIF_Custom(X1 As String, Month_X As String)
    Dim MonthArray(1 To 12, 1 To 2) As Variant

    MonthArray(1, 1) = "January"
    MonthArray(2, 1) = "February"
    MonthArray(3, 1) = "March"
    MonthArray(4, 1) = "Apr"
    MonthArray(5, 1) = "May"
    MonthArray(6, 1) = "June"
    MonthArray(7, 1) = "July"
    MonthArray(8, 1) = "August"
    MonthArray(9, 1) = "September"
    MonthArray(10, 1) = "October"
    MonthArray(11, 1) = "November"
    MonthArray(12, 1) = "December"

    MonthArray(1, 2) = "1"
    MonthArray(2, 2) = "2"
    MonthArray(3, 2) = "3"
    MonthArray(4, 2) = "4"
    MonthArray(5, 2) = "5"
    MonthArray(6, 2) = "6"
    MonthArray(7, 2) = "7"
    MonthArray(8, 2) = "8"
    MonthArray(9, 2) = "9"
    MonthArray(10, 2) = "10"
    MonthArray(11, 2) = "11"
    MonthArray(12, 2) = "12"

    For x = 1 To 12
        If Month_X = MonthArray(x, 1) Then
            Month_X = MonthArray(x, 2)
        End If
    Next x

    CountIF_Custom = Application.CountIfs(Sheets("SomeSheet").Range("SomeRange"), X1, Sheets("SomeSheet").Range("SomeRange"), Month_X)

    End Function

不需要数组,您可以使用带有 MonthName 函数的 for 循环:

Function CountIF_Custom(X1 As String, Month_X As String)

Dim x As Integer

For x = 1 To 12
    If Month_X = MonthName(x) Then
        Month_X = CStr(x)
        Exit For
    End If
Next x

CountIF_Custom = Application.CountIfs(Sheets("SomeSheet").Range("SomeRange"), X1, Sheets("SomeSheet").Range("SomeRange"), Month_X)

End Function