Home > Software engineering >  Return string element from array given index
Return string element from array given index

Time:05-31

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.

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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.

  • Related