简体   繁体   中英

Excel VBA Combobox

I have a ComboBox in a userform, and I'm looking for a method to use to find what the selection is so that I can utilize that as a string and pass it to a cell on the sheet. For instance:

 Private Sub Filter_Click()
 'The Userform is called Summary, and the ComboBox in question is named Month_Filter
 If Summary.Month_Filter = "January" Then .......
 Call UpdatedTotals
 End Sub


 Sub UpdatedTotals()
 Dim ChosenDate as String
 If Summary.Month_Filter <> "" Then ChosenDate = Summary.Month_Filter.Value
 Range("A1").FormulaR1C1 = ChosenDate
 End Sub

The value of the combobox is accessible using:

Me.comboBoxName.Value

So something like:

If Me.comboBoxName.Value = "January" Then ....

would work.

However, this only applies to code written in the form's code (if that makes sense). You won't be able to use that code in a separate module as it won't know anything about Me.comboBoxName... If you want to use that value in a different module you would have to pass the value when calling that sub/function.

The Value property will return the value of the BoundColumn for the selected list item.

The ListIndex property returns the index (starting at zero for the first item) of the selected list item. It can be used with Column to get the right value if the value you're looking for is not in BoundColumn .

ChosenDate = Summary.Month_Filter.Column(Summary.Month_Filter.ListIndex,1)

The second argument, 1, refers to the second column as it's zero-based just like the list items.

Try this:

Private Sub Filter_Click()
 If Summary.Month_Filter.Value = "January" Then .......
 Call UpdatedTotals
 End Sub


 Sub UpdatedTotals()
 If Summary.Month_Filter.Value <> "" Then Range("A1").Value = Summary.Month_Filter.Value
 End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM