Home > Back-end >  Excel VBA code for Populate date based on combobox selection
Excel VBA code for Populate date based on combobox selection

Time:01-23

First off all I am not very experienced with excel VBA. After searching on net and youtube I couldn't figure it out, so I hope you can help me out.

I have 2 items in ComboBox1, one is Cardio Only and second is Gym Only. I want to auto populate Renew Date in TextBox8 based on Combobox1 selection.

Like, if i select "CARDIO ONLY" then Next Renew date should be 90days currentdate or 3 months current date in TextBox8. If i select "GYM ONLY" then Next Renew date should be 30days currentdate or 1 month currentdate in TextBox8.

I.e (in days)

90 22/01/2022 = 22/04/2022

30 22/01/2022 = 21/02/2022

(in months)

3 22/01/2022 = 22/04/2022

1 22/01/2022 = 21/02/2022

Your help is appreciated.

Thanks in advance!

Sherry

CodePudding user response:

Use this to add 3 months to the current date:

DateAdd("m", 3, Date)

this to add 90 days to the current date

DateAdd("d", 90, Date)

Note that adding days and adding months does not always yield the same result, depending on the number of days in the months.

E.g. DateAdd("m", 1, #2002/1/30#) yields 2002/02/28.

But DateAdd("d", 30, #2002/1/30#) yields 2002/03/01.

See also: DateAdd function

CodePudding user response:

Private Sub ComboBox1_Change()

   Dim mth As Long
   Select Case Me.ComboBox1.Value
       Case "GYM ONLY"
           mth = 1
       Case "CARDIO ONLY"
           mth = 3
   End Select
   If mth > 0 Then
       Me.TextBox8 = Format(DateAdd("m", mth, Date), "dd/mm/yyyy")
   End If

End Sub
  •  Tags:  
  • Related