我有一个复选框列表,在检查了一些复选框后,我想知道检查了哪些复选框,以便我可以使用这些复选框。不知道为什么这几行不起作用。执行后会出现一条弹出错误消息,提示“需要对象”运行时错误'424':并突出显示line => ReDim SelectedItemArray(ListBox1.ListCount)As String。是的我有四个ListBox; ListBox1,ListBox2,ListBox3,ListBox4。任何帮助表示赞赏。谢谢
Sub CheckedBoxes()
Dim SelectedItemArray() As String
ReDim SelectedItemArray(ListBox1.ListCount) As String
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) = True Then
SelectedItemArray(i) = ListBox1.List(i)
End If
Next
End Sub
答案 0 :(得分:2)
您需要完全限定列表框。例如Sheet1.ListBox1.ListCount
答案 1 :(得分:1)
这是我在UserForm上用于ListBoxes的函数。我修改了它(在下面的下面)以便在Worksheet列表框中使用。
对于UserForm上的表单控件ListBox,请将其命名为:
myArray = GetSelectedItems(ListBox1)
这里的函数将接受来自UserForm的任何列表框作为命名参数:
Public Function GetSelectedItems(lBox As MSForms.ListBox) As Variant
'returns an array of selected items in a ListBox
Dim tmpArray() As Variant
Dim i As Integer
Dim selCount As Integer
selCount = -1
For i = 0 To lBox.ListCount - 1
If lBox.Selected(i) = True Then
selCount = selCount + 1
ReDim Preserve tmpArray(selCount)
tmpArray(selCount) = lBox.List(i)
End If
Next
If selCount = -1 Then
GetSelectedItems = Array()
Else:
GetSelectedItems = tmpArray
End If
End Function
如果您在工作表上引用ListBox,请改为尝试:
这样称呼:
myArray = GetSelectedItems(Sheet1.Shapes("List Box 1").OLEFormat.Object)
这里是为Worksheet表单控件ListBox修改的函数:
Public Function GetSelectedItems(lBox As Object) As Variant
'returns an array of selected items in a ListBox
Dim tmpArray() As Variant
Dim i As Integer
Dim selCount As Integer
selCount = -1
For i = 1 To lBox.ListCount - 1
If lBox.Selected(i) = True Then
selCount = selCount + 1
ReDim Preserve tmpArray(selCount)
tmpArray(selCount) = lBox.List(i)
End If
Next
If selCount = -1 Then
GetSelectedItems = Array()
Else:
GetSelectedItems = tmpArray
End If
End Function