问题
I have this vba userform combobox that shows time range. In the rowsource, i have inputted 12:00 PM. But everytime i click 12:00 PM in the combobox, it shows 12:05 AM instead. Any idea how to solve this problem?
回答1:
Use click event instead of change event
Private Sub ComboBox5_Click()
Dim t As Double
With ComboBox5
t = Val(.List(.ListIndex))
.Value = Format(t, "hh:mm:ss AM/PM")
End With
End Sub
回答2:
A ComboBox handles text strings. Excel records time as a fraction of 1. 12:00 PM = 0.5 (half a day). Therefore the first question is what you loaded into your ComboBox. Did you load a number like "0.5" - as string, of course, because the ComboBox only takes strings (VBA may have done the conversion for you without notification) - or as a text string, like "12:00 PM". Either way, the ComboBox will hold whatever you have in the RowSource range.
The other question is how the ComboBox converts the string in its list to the string it displays. Conversion is done by means of the cell format in Excel and the Format() function in VBA. The fact that a different time is shown points to a conversion taking place. Look for code that runs on one of the ComboBox's events, for example the Change event.
T take control I suggest that you import text strings into your ComboBox, like "12:00 PM". If you load text strings the drop-down will show them correctly both in the list and in the Cbx. When you want to use a Cbx value in calculations use the TimeValue() function for conversion.
Dim MyTime As Double
MyTime = TimeValue(ComboBox1.Value)
Will assign the correct numberr to MyTime if the string in the Cbx represents a time in a format your computer understands. The best way to make sure of this is to store the values as true Times (meaning 0.5 for 12:00 PM) and convert these values to a time string when you load them into the Cbx. Use code like Format(0.5, "hh:mm AM/PM") for the conversion. Replace "0.5" with a variable of double data type. If you wish to continue using the RowSource range, set it up with formulas like this in it, =Text(A1, "hh:mm AM/PM") where A1 holds the true time.
来源:https://stackoverflow.com/questions/61493230/input-1200-pm-on-vba-userform-combobox