Setting value of a UserForm Combobox

2019-02-28 04:44发布

问题:

(Narrowed down from my broader question at enter link description here as advised in meta.)

I have a userform. On that userform are several comboboxes for selection year, month and day. The day combobox is populated with numbers up to 28, 29, 30 or 31 depending on what year and month is selected. To avoid selecting things like the 31st of February, I'd like to check if the selected day value exceeds the maximum for that month, and reduce it appropriately. At the moment I've tried these options:

If Me.Combo_Day.Value > iMaxDate And iMonthNo > 0 And Not Me.Combo_Day.Value = "" Then Me.Combo_Day.Value = Me.Combo_Day.List(iMaxDate - 1)

and

If Me.Combo_Day.Value > iMaxDate And iMonthNo > 0 And Not Me.Combo_Day.Value = "" Then Me.Combo_Day.Value = iMaxDate

Neither of them work; any time that line gets parsed, I get a 380 error with the explanation "Could not set the Value property. Invalid property value."

I've tried changing both .Text and .Value, and neither seem to make much difference. How do I change the selected value in a combobox?

回答1:

Edit due to a misunderstanding of reqs:

My fault, I misunderstood the original post. If the days are set in numerical order, you can indeed use the ListIndex (just remember it starts with zero, so you'll have to subtract 1). It would look like:

Me.Combo_Day.ListIndex = (iMaxDate - 1)

Does that work?