addohm
addohm

Reputation: 2475

VBA ComboBox Value by Index

I've got a form that contains a combobox which contains the values

With io6
   .AddItem "90°"
   .AddItem "180°"
   .AddItem "270°"
   .AddItem "360°"
End With

The member of this method I am actually using is .ListIndex. When a user selects 270 degrees, I am sending a 2 to a variable. When I read the variable, I want have the combobox correctly show the appropriate value. In other words, if the variable is 1, I want the combo box to show 180 degrees. Is that achievable without a select\if statement that writes into .Value?

Sub varChange(val as integer)

   With comboBox

     Select Case val
       Case 1
         .value = "90°"
       Case 2
         .value = "180°"
       Case 3
         .value = "270°"
       Case 4
         .value = "360°"
     End Select

    End With

End Sub

The most direct I can ask this question is, can the method element be set based on the index? Can I set the combo box element based on the index rather than having to write in a new value?

Upvotes: 2

Views: 42799

Answers (3)

hammythepig
hammythepig

Reputation: 957

The most direct I can ask this question is, can the method element be set based on the index? Can I set the combo box element based on the index rather than having to write in a new value?

Yes,
I used the following line:

io6.ListIndex = val - 1

So in your code it's:

Sub varChange(val as integer)
    comboBox.ListIndex = val - 1
End Sub

Upvotes: 0

braX
braX

Reputation: 11755

sValue = combobox.List(combobox.ListIndex,0)

Upvotes: 0

Sam
Sam

Reputation: 5731

I'm not sure if I got it right, but I think you want to get the list index of the selected item. You can get that by

x = io6.ListIndex + 1

The +1 is there since ListIndex is 0 based, but you wanted it 1 based.
And something completely different,
Remove the brackets. Method calls without return values does not use them in VBA

Edit after comment
To take this the other way, i.e getting a value from an index value, do like this:

y = io6.List(x - 1)

Upvotes: 5

Related Questions