Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Populate current months for current year in combobox on form

0

Hello

I would fix my problem by add months from 1-12 months  in combobox1 like JAN-24 , FEB-24 

it doesn't show DEC-24 it will show DEC-23

Private Sub UserForm_Activate()



Dim MyDate As Date
    Dim i As Integer
    MyDate = Date
    For i = 1 To 12
        Me.ComboBox1.AddItem Format(MyDate, "mmm-yy")
        MyDate = DateAdd("m", -1, MyDate)
    Next

End Sub

thanks

Answer
Discuss

Answers

0
Selected Answer

Hi again Ali M

If you want the UserForm to show the months of the current year (e.g. JAN-24 to DEC-24), your code should be replaced by the following (changes in bold):

Private Sub UserForm_Activate()



Dim MyDate As Date

    Dim i As Integer

    ' get January of this year

    MyDate = DateValue("01/01/" & Year(Date))

    For i = 1 To 12

        ' add months of this year

        Me.ComboBox1.AddItem Format(MyDate, "mmm-yy")

        MyDate = DateAdd("m", 1, MyDate)

    Next



End Sub

The attached revised file has that code and works when you click the button.

If however you want to add the current month plus the next 11 months (e.g. Nov-24 to Oct-24) instead, just remove the minus sign (-) from the line within the loop in your code which updates MyDate (see changes in bold below):

Private Sub UserForm_Activate()
    
    Dim MyDate As Date
    Dim i As Integer
    MyDate = Date
    For i = 1 To 12
        ' add future months
        Me.ComboBox1.AddItem Format(MyDate, "mmm-yy")
        MyDate = DateAdd("m", 1, MyDate)
    Next

End Sub
 

The above code is also in the attached file but is commented out (you'd need to uncomment it and delete the other code if this is what you want).

Hope one of these solutions fixes your problem. If so, please remember to mark this Answer as Selected.

Discuss

Discussion

Thanks John.
Ali M (rep: 34) Nov 18, '24 at 12:09 pm
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login