问题
I'm still pretty new to VBA, but I have two activex listboxes on a worksheet. On one listbox I have salesperson names (called lstNames) and the other listbox has locations (lstSite). What I'm trying to achieve is the following:
- Select name from lstNames
- Selection from lstNames generates lstSite with a list of a few locations associated with the name.
For example, if I select Bob from the lstNames listbox, then the lstSites listbox will populate all of Bob's sites like NY, CO, CA, PA. If I select Susan from lstNames, then lstSites will clear Bob's and add Susan's sites which are TX, WA, OR, etc.
Both lstNames and lstSite pull from the same worksheet which is formated:
Column 1: Names
Column 2: Site
I've been trying to do a Vlookup to add items to the listbox, but it's not working. I know I can do a select case statement and add the sites manually, but I want to program a good code that will run through them automatically.
Select Case lstNames.Value
Case "Bob"
lstSites.AddItem WorksheetFunction.VLookup(lstDM.Text, wkbhcsfdata.Worksheets("Names+Sites").Range("Sites"), 1, False)
End Select
回答1:
Try to if this helps get the range addresses you need. For this, I used named ranges for Persons and another for Locations. The variable strPerson could be replaced with a cell value.
Dim ws As Worksheet
Set ws = Worksheets("sheet2")
Dim rngPerson, rngLoc As Range
Set rngPerson = ws.Range("Person")
Set rngLoc = ws.Range("Location")
Dim iMatch, iCount As Integer
Dim strPerson As String
strPerson = "Bob"
iMatch = WorksheetFunction.Match(strPerson, rngPerson, 0)
iCount = WorksheetFunction.CountIf(rngPerson, strPerson)
Dim rngList As Range
Set rngList = ws.Range(rngLoc.Rows(iMatch), rngLoc.Rows(iMatch + iCount - 1))
Once you have the dynamic range of rngList, you can loop on rngList using something like:
For Each rw in rngList.rows
[Your code to insert list items]
Next
All this would need to be in the ActiveX event.
Edit: Changed .Cells to .Rows
来源:https://stackoverflow.com/questions/39170771/listbox-generates-secondary-listbox-based-on-selection