我有一个需要增强的工作宏。宏的一部分填充Excel用户窗体中的列表框。代码如下:
Dim objExcelApp As Object
Dim objExcelWorkBook As Object
Dim objExcelWorksheet As Object
Dim varTest As Variant
lngLastLitRow = objExcelApp.Sheets(1).UsedRange.Rows.Count
Dim strArray() As Variant
ReDim strArray(lngFilteredRowCount - 1, 2)
'Load strArray
With objExcelWorkBook.Sheets(1)
'The ListBox dimention starts with (0), so set lngListBoxRow
lngListBoxRow = 0
'Loop through all the rows in rngLiturgies
For Each rngCurrentLitRow In rngLiturgies.Rows
'Populate lngExcelRow
lngExcelRow = rngCurrentLitRow.Row
'Select only the rows that are NOT filtered
If rngCurrentLitRow.EntireRow.Hidden = False Then
'Fill the array row (lngListBoxRow) with Excel data (lngExcelRow)
'The Array's column 0 equates to Excel's column 1
strArray(lngListBoxRow, 0) = objExcelWorkBook.Sheets(1).Cells(lngExcelRow, 1)
strArray(lngListBoxRow, 1) = objExcelWorkBook.Sheets(1).Cells(lngExcelRow, 2)
strArray(lngListBoxRow, 2) = objExcelWorkBook.Sheets(1).Cells(lngExcelRow, 3)
'Increment lngListBoxRow "manually" since it doesn't correspond to
'the Excel row in the FOR loop
lngListBoxRow = lngListBoxRow + 1
Else
End If
Next rngCurrentLitRow
End With
'Load ListBoxLit with strArray
With ListBoxLit
.ColumnCount = 3
.List = strArray
End With
作为一项增强功能,只要其他表单字段中的值发生更改,我就会默认列表框中的行。基于该字段更改,我将知道与数组中的元素对应的三个变量的值。当我有三个值可用时,如何选择列表框中的行? 谢谢你看这个。
答案 0 :(得分:1)
Selected
类的MSForms.ListBox
方法采用单个参数 index ,这是列表中的位置。
Sub SelectItemInListBox(val$, lBox as MSForms.ListBox)
Dim i as Long
For i = 0 to lBox.ListCount - 1
If LBox.List(i) = val Then LBox.Selected(i) = True
Next
End Sub
您可以调用这样的函数,并传递您想要选择的值,以及列表框对象本身,例如:
Call SelectItemInListBox("some value", ListBoxLit)
如果你有三个值,你可以调用这个函数三次。