Excel 选择列表框 Vba 中的所有项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42145601/
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-12 12:05:39  来源:igfitidea点击:

Excel Select all items in Listbox Vba

excelvba

提问by Ricklou

I am stumped I tried the following and for the life of me I cant figure this out....Need to use a comand button on a listbox on an excel vba form.

我很难过,我尝试了以下操作,但在我的一生中,我无法弄清楚这一点......需要在 excel vba 表单上的列表框中使用命令按钮。

Iniatilizing the form on load.....it load fine

在加载时初始化表单......它加载良好

Sub UserForm_Initialize()
UserForm1.LbNumbers.RowSource = "Sheet2!A1:A3"End Sub

Items display in listbox fine

项目显示在列表框中很好

I have a command button under the list box to select all the code

我在列表框下有一个命令按钮可以选择所有代码

Sub CbSelectall_Click()
   For i = 0 To LbNumbers.ListCount - 1
      LbNumbers.Selected(i) = True
   Next i
End Sub

If I click on button it jumps to the last line but it doesnt select all the numbers in the listbox. Can someone tell me how can I rectify it to select all the numbers in the listbox.Thank you

如果我单击按钮,它会跳到最后一行,但不会选择列表框中的所有数字。有人可以告诉我如何纠正它以选择列表框中的所有数字。谢谢

采纳答案by Tú Tú

Private Sub lbTraderId_Change()
    If ResetListBox(lbTraderId) Then
        Exit Sub
    ElseIf lbTraderId.Selected(0) Then
        For i = 1 To lbTraderId.ListCount - 1
            If lbTraderId.Selected(i) = False Then
                lbTraderId.Selected(i) = True
            End If
        Next i
    ElseIf lbTraderId.Selected(0) = False Then
        For i = 1 To lbTraderId.ListCount - 1
            If lbTraderId.Selected(i) = True Then
                lbTraderId.Selected(i) = False
            End If
        Next i
    End If
End Sub

Private Function ResetListBox(lbx As MSForms.ListBox) As Boolean
    Dim x As Long
    Static bExit As Boolean
    If Not bExit Then
        x = lbx.ListIndex
            If x >= 0 And Not lbx Is Me.lbTraderId Then
                bExit = True
                lbx.Selected(x) = Not lbx.Selected(x)
                bExit = False
                ResetListBox = True
            End If
    End If
End Function