问题
How can I get the value of a listbox in a userform to dynamically change when the user changes the value of a another list box in the same userform. The main portion that is giving me trouble is lstMonth. The value of lstMonth should equal the months, which correlate to the data in different sheets that will show in the first listbox. I will provide a picture of the form and data so that this all makes more since.
Code
Option Explicit
Private Sub cmdCalc_Click()
'declare variables and assign address to rngData variable
Dim strId As String, intRow As Integer, intNumSales As Integer, curSales As Currency
Dim rngData As Range
Set rngData = Application.Workbooks("t13-ex-e4d.xls").Worksheets("jan").Range("a3").CurrentRegion
'assign selected list box item to strId variable
strId = lstId.Value
'locate first occurrence of ID
intRow = 2
Do Until rngData.Cells(RowIndex:=intRow, columnindex:=4).Value = strId
intRow = intRow + 1
Loop
'accumulate and count salesperson's sales, stop when loop encounters different ID
Do While rngData.Cells(RowIndex:=intRow, columnindex:=4).Value = strId
curSales = curSales + rngData.Cells(RowIndex:=intRow, columnindex:=3).Value
intNumSales = intNumSales + 1
intRow = intRow + 1
Loop
'display appropriate amount
If optTotal.Value = True Then
lblAnswer.Caption = Format(expression:=curSales, Format:="currency")
Else
lblAnswer.Caption = Format(expression:=curSales / intNumSales, Format:="currency")
End If
End Sub
Private Sub cmdCancel_Click()
'close custom dialog box
Unload frmSalesCalc
End Sub
Private Sub UserForm_Initialize()
lstMonth.Value = Application.Workbooks("T13-EX-E4D.xls").ActiveSheet.Range("b3").CurrentRegion
End Sub
回答1:
On the form open fill the month listbox with all avaible sheets
' Declare Current as a worksheet object variable.
Dim Current As Worksheet
' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
' Insert your code here.
ListBox_Month.AddItem Current.Name
Next
The rest is basicaly to fill the other listbox if the month List is clicked, with all the avaible id's. So in the Listbox_Change Method you Need something like this:
Dim sales_ids as Variant
sales_ids = UniquesFromRange(Worksheets(Listbox_Month.value).Range(D))
Function UniquesFromRange(rng As Range)
Dim d As Object, c As Range, tmp
Set d = CreateObject("scripting.dictionary")
For Each c In rng.Cells
tmp = Trim(c.Value)
If Len(tmp) > 0 Then
If Not d.Exists(tmp) Then d.Add tmp, 1
End If
Next c
UniquesFromRange = d.keys
End Function
Now you have all the id's, fill them in the second listbox, and voila, the rest should be clear, but just ask if you still have questions
来源:https://stackoverflow.com/questions/36415648/getting-the-value-of-a-listbox-to-dynamically-change-with-worksheets