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

Move date out one month or year
Use =EDATE(A2,1) for one month later. Use EDATE(A2,12) for one year later.
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,214,790
Messages
6,121,608
Members
449,038
Latest member
apwr

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