PDA

View Full Version : VBA array difficulty



yoleven
02-05-2011, 02:57 PM
I have this program that writes the months of the year across the top.
The user is promted for a month, then the entered month appears first followed by the array of months in that order.
So if you entered in Mar, Mar appears in the first cell followed by Apr, May, etc.
Here is what I have:

Sub months()
Dim months(12) As String
Dim enter_month As String, i As Integer, j As Integer

Cells(3, 1) = "Jan"
Cells(3, 2) = "Feb"
Cells(3, 3) = "Mar"
Cells(3, 4) = "Apr"
Cells(3, 5) = "May"
Cells(3, 6) = "Jun"
Cells(3, 7) = "Jul"
Cells(3, 8) = "Aug"
Cells(3, 9) = "Sep"
Cells(3, 10) = "Oct"
Cells(3, 11) = "Nov"
Cells(3, 12) = "Dec"

'read values into array

For i = 1 To 12
months(i) = Cells(3, i)
Next i

'get month from user

enter_month = InputBox("enter a month")

For j = 1 To 12
For i = 1 To 12
If months(i) = enter_month Then Cells(4, j) = months(i)
cells(4,j+1)=months(i)

Next i
Next j

End Sub

I'm stuck here because when I run the program and view it with a line break, It pretty much does what I want but it puts the values of the array into each cell but it cyles through the whole array until I get "Dec" in each cell.
Please help me here, I'm new to arrays and VBA and I don't really know what to do.

Kenneth Hobs
02-05-2011, 03:43 PM
Welcome to the forum!

Sub months()
Dim months() As Variant
Dim enter_month As String, i As Integer, j As Integer
Dim x As Long, d As Date

Cells(3, 1) = "Jan"
Cells(3, 2) = "Feb"
Cells(3, 3) = "Mar"
Cells(3, 4) = "Apr"
Cells(3, 5) = "May"
Cells(3, 6) = "Jun"
Cells(3, 7) = "Jul"
Cells(3, 8) = "Aug"
Cells(3, 9) = "Sep"
Cells(3, 10) = "Oct"
Cells(3, 11) = "Nov"
Cells(3, 12) = "Dec"

'read values into array
months() = Range("A3:L3").Value

'get month from user
enter_month = InputBox("enter a month")
x = index(months(), enter_month)
If x = -1 Then Exit Sub

For i = 0 To 11
d = DateAdd("m", i, DateSerial(2011, x, 1))
Cells(4, i + 1) = Format(d, "MMM")
Next i
End Sub

'val is not case sensitive
Function index(vArray() As Variant, val As Variant) As Long
On Error GoTo Minus1
index = WorksheetFunction.Match(val, WorksheetFunction.Transpose(vArray), 0)
Exit Function
Minus1:
index = -1
End Function