有人可以帮帮我吗?我正在尝试在ListBox上选择一些项目(使用复选框),以匹配指定Excel工作表和范围中的值。 (从BR5 up to BR17
说,但通常我会在3/4单元格中有值。)
以下代码选择所有项目,但我只想选择范围为BR5及以后的项目
Dim x As Integer
For x = 0 To lstDataTracing.ListCount - 1
If lstDataTracing.Selected(x) = False Then
lstDataTracing.Selected(x) = True
End If
Next
我想知道我是否可以将上述代码合并到下面的代码中 - 这就是我需要帮助的地方。
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = UBound(Filter(arr, stringToBeFound)) > -1
End Function
Dim itemExistResults As Boolean
'this populate my listbox - lstDataTracing
myArray = Array("a", "b", "c", "d", "e", "f")
'this part isn’t working – need looping!
If IsInArray(Range("BR5:BR17"), myArray) = True Then
itemExistResults = True
'If I could get the index number for the matched item,
'then using the index number I could probably select the items on the ListBox.
'just for test purpose
MsgBox "Yes! Item is not in the array"
Else
'just for test purpose
MsgBox "No! Item is not in the array"
End If
答案 0 :(得分:0)
就像我在上面的评论中提到的那样,由于只有12个单元格,实现所需内容的最简单方法是不循环遍历列表框和范围,然后设置.Selected(x) = True
见这个例子。
Private Sub UserForm_Initialize()
Dim i As Long
'~~> Adding test numbers
For i = 1 To 15
lstDataTracing.AddItem i
Next i
End Sub
Private Sub CommandButton1_Click()
Dim x As Integer
Dim ws As Worksheet
Dim rng As Range
'~~> Change this to th relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Set rng = ws.Range("BR5:BR17")
For x = 0 To lstDataTracing.ListCount - 1
If Application.WorksheetFunction.CountIf(rng, lstDataTracing.List(x)) Then
lstDataTracing.Selected(x) = True
Else
lstDataTracing.Selected(x) = False
End If
Next
End Sub
<强>截图强>