简体   繁体   中英

VBA Excel Return values from an array with loop

I have a small loop in my vba function, which gives me for each Month - ie Parameter - the respective contract from a list and works for every month except December. Contractlist is a vertical array (3,5,7,9,12). This is the code:

 k = 1 Do Until Month(Parameter) < contractlist(k, 1) k = k + 1 Loop nextcontract = MonthName(contractlist(k, 1)) 

Here is the problem: When the month is December, month(December) is never smaller than contractlist(k, 1) because 12 is the smallest value in that array. In that case, I would like to just jump to the first value of the array, ie "3". In other words, in the last line nextcontract should be MonthName(contractlist(1, 1)). Can somebody give me a hint how to do that?

Thanks, your help is really appreciated!

There's a sneaky way to cheat that uses MOD
As mod will reduce a value to 0 when it equals the value looked for (and multiples), we can use this so the Month when you get December from your parameter will be zero, instead of 12...

Do Until (Month(Parameter) Mod 12) < contractlist(k, 1)

This will leave every other month alone, but will return 0 for December.

I understand better now what you're doing. I've edited my solution below. Don't be afraid to use more variables. Sometimes you can be using one variable to do too much and it makes it hard to see a solution.

' My test data
Dim contractlist(1 To 5, 1 To 1) As Integer
contractlist(1, 1) = 3
contractlist(2, 1) = 5
contractlist(3, 1) = 7
contractlist(4, 1) = 9
contractlist(5, 1) = 12

Dim month As Integer ' represents Month(Parameter)
month = 12

' Solution
Dim contractCount As Integer
Dim nextContractNum As Integer
Dim nextcontract As String
contractCount = UBound(contractlist, 1)

' Next contract is the first in the list
' if we don't find a later one
nextContractNum = contractlist(1, 1)

For i = 1 To contractCount
    If month < contractlist(i, 1) Then
        nextContractNum = contractlist(i, 1)
        Exit For
    End If
Next i

nextcontract = MonthName(nextContractNum)

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