默认为 Excel 列表框中的特定行

Defaulting to a particular row in an Excel listbox

我有一个需要改进的工作宏。宏的一部分填充 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

作为改进,我想在另一个表单字段中的值发生更改时将列表框中的行设置为默认值。基于该字段的变化,我将知道对应于数组中的元素的三个变量的值。当我有这三个值可用时,如何 select 列表框中的行? 感谢您查看此内容。

MSForms.ListBox class 的 Selected 方法采用单个参数 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

您可以这样调用一个函数,并将您想要的 和列表框对象本身传递给 select,例如:

Call SelectItemInListBox("some value", ListBoxLit)

如果您有三个值,则只需调用此函数三次即可。