Excel VBA:列表框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5088787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:42:56  来源:igfitidea点击:

Excel VBA: Listbox

listboxexcel-vbavbaexcel

提问by Melvin Heng

Let's say I have a range of values as such:

假设我有一系列的值:

Customer | Services | Cost  | Paid
Mel      | Abc      | .00 | TRUE
Mel      | Def      | .00 | FALSE
Xin      | Abc      | .00 | TRUE
Titus    | EEE      | .00 | TRUE

and I want these items to be inserted into a listbox. However I have a few criteria, which is to display the items only specific to the user (e.g. Mel or Xin or Titus), and display only when "False". How am I to do so, thanks in advance.

我希望将这些项目插入到列表框中。但是我有一些标准,即仅显示特定于用户的项目(例如 Mel 或 Xin 或 Titus),并且仅在“False”时显示。我该怎么做,提前致谢。

What I have now:

我现在所拥有的:

Dim lbtarget As MSForms.ListBox
Dim rngSource As Range
Set rngSource = Range("Table1")    
Set lbtarget = Me.ListBox1
With lbtarget
    'Determine number of columns
    .ColumnCount = 4
    'Set column widths
    .ColumnWidths = "50;80;100"
    'Insert the range of data supplied
    .List = rngSource.Cells.Value
End With

采纳答案by chris neilsen

Replace

代替

.List = rngSource.Cells.Value

with

For Each rw In rngSource.Rows
    If rw.Cells(1,1) = <Specify User> And rw.Cells(1,4) = FALSE Then
        .AddItem ""
        For i = 1 To .ColumnCount
            .List(.ListCount - 1, i - 1) = rw.Value2(1, i)
        Next
    End If
Next

Whole Sub using Mel as the user

使用 Mel 作为用户的 Whole Sub

Private Sub CommandButton1_Click()
    Dim lbtarget As MSForms.ListBox
    Dim rngSource As Range
    Dim rw As Range
    Dim i As Long

    Set rngSource = Range("Table1")
    Set lbtarget = Me.ListBox1
    With lbtarget
        .ColumnCount = 4
        .ColumnWidths = "50;80;100"
        For Each rw In rngSource.Rows
            If rw.Cells(1, 1) = "Mel" And rw.Cells(1, 4) = False Then
                .AddItem ""
                For i = 1 To .ColumnCount
                    .List(.ListCount - 1, i - 1) = rw.Cells(1, i)
                Next
            End If
        Next
    End With

End Sub