根据Excel单元格值检查/取消检查Listobx项目

有人可以帮我吗? 我试图select一些项目(使用checkbox)在一个列表框匹配指定的Excel工作表和范围的值。 (比如从BR5 up to BR17 ,但通常我会在3/4个单元格中有值)。

下面的代码select所有项目,但我只想selectBR5范围内的项目

 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 

就像我在上面的评论中提到的那样,因为只有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 

截图

在这里输入图像说明