Drawleeh
Drawleeh

Reputation: 259

Return string element from array given index

I have the following code:

     Dim CurrMonth As Integer
     Dim MonthPos As Variant
     Dim CurrPos As Integer
     
     
     CurrMonth = Month(Date) - 1
     MonthPos = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")

Could anyone provide guidance on how I would be able to get (in this case) the string element from the Array MonthPos given the index CurrMonth.

Upvotes: 0

Views: 117

Answers (4)

T.M.
T.M.

Reputation: 9948

Assuming Excel (to evaluate the months name array in one go) the following approach allows to input any increments or decrements as optional second argument:

Function getMonth(currMonth As Long, Optional MonthOffset As Long = 0)
'a) build array of month names via evaluation (Excel)
    Dim months(): months = [Text(Date(0,Column(A:L),1),"mmmm")]
'b) calculate wanted month
    currMonth = (currMonth + MonthOffset + 12) Mod 12
    If currMonth = 0 Then currMonth = 12
'c) return month name
    getMonth = months(currMonth)
End Function

Example call

Simply pass a possible decrement as 2nd argument:

   Debug.Print getMonth(1)              ' ~~> returns January
   Debug.Print getMonth(1,-1)           ' ~~> returns December
   'assuming call as of 5/31 2022, i.e. equalling getMonth(5) 
   Debug.Print getMonth(Month(Date))    ' ~~> returns May
   Debug.Print getMonth(Month(Date),-1) ' ~~> returns April
    

Upvotes: 1

Pᴇʜ
Pᴇʜ

Reputation: 57683

Instead of the array you can also use

Format$(date,"MMMM")

or if you need the previos month then

Format$(DateSerial(Year(Date),Month(Date)-1,1),"MMMM")

to get the name of the month in the language of the operating system.

Upvotes: 1

Reporter
Reporter

Reputation: 3948

https://www.softwaretestinghelp.com/vba-array-tutorial/#One_Dimensional_Array offers following example:

Private Sub arrayExample3()
Dim thirdQuarter(13 To 15) As String 'creates array with index 13,14,15
thirdQuarter(13) = "July"
thirdQuarter(14) = "Aug"
thirdQuarter(15) = "Sep"
MsgBox "Third Quarter in calendar " & " " & thirdQuarter(13) & " " &
        thirdQuarter(14) & " " & thirdQuarter(15)
End Sub

So for your case should be:

MonthPos(CurrMonth)

Upvotes: 1

FaneDuru
FaneDuru

Reputation: 42236

Please, use the next adapted way:

Sub extractMonth()
  Dim CurrMonth As Long, MonthPos As Variant, CurrPos As Integer, prevMonth
 
     CurrMonth = Month(Date) - 1
     MonthPos = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
     prevMonth = MonthPos(CurrMonth - 1) '- 1 because it is a zero based 1D array...
     Debug.Print prevMonth 'the previous month (I could see Month(Date) - 1) and I supposed that this is needed.
                           'otherwise, you should simple use MonthPos(CurrMonth), for the current month
End Sub

Upvotes: 2

Related Questions