listbox, select item based on cell/variable value vba

smakatura

Board Regular
Joined
May 27, 2011
Messages
141
I have a listbox that allows for multiple selections. However I want to select just one of theitems based on a variable value.


So I will set variable “Department” to the value in cellD28


Then use that variable to select just that one item from themultiselect listbox.
Prior to thisselection, there will be no items selected in the listbox.



Code:
 Dim Department As String
 
 Department = Range("D28")
 With Sheets("Distribution").OLEObjects("ListBox1").Object
    For i = 0 To .ListCount - 1
        if .selected(i) =  Department
            .Selected(i) = True
        End If
        
    Next i
 End With
 
Last edited:

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
How about
Code:
 Dim Department As String
 Dim i As Long
 Department = Range("D28")
 With Me.ListBox1
    For i = 0 To .ListCount - 1
        If .List(i) = Department Then
            .Selected(i) = True
        End If
    Next i
 End With
 
Upvote 0
Thanks, I got an error stating that the ME command had an issue... but I did get it working
Fix: made
Code:
if .selected(i) =  Department
into
Code:
If .List(i) = Department Then

at the very lease I forgot the "then"...not sure what I was thinking


the full code that worked was
Code:
 Dim i As Long
 Dim Department As String
 
 Department = Range("D28")
 With Sheets("Distribution").OLEObjects("ListBox1").Object
    For i = 0 To .ListCount - 1
        If .List(i) = Department Then
            .Selected(i) = True
        End If
        
    Next i
 End With

thank you for the help
 
Upvote 0
You're welcome & thanks for the feedback
 
Upvote 0

Forum statistics

Threads
1,223,958
Messages
6,175,629
Members
452,661
Latest member
Nonhle

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top