简体   繁体   中英

Excel VBA UDF Count Ifs with data conversion

I am attempting to write a UDF using Countifs. I want the user to be able to select criteria 1 (held as X1) and the month (held as month_X). The month in the lookup table is in numbers so I want the function to convert the month name to the month number.

This works - but is there a better way to convert the data? Ie less lines of code?

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

No need for the array, you can use a for loop with the MonthName function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM