尝试设置所选项目的ComboBox导致编译错误

时间:2018-02-20 12:22:54

标签: vba excel-vba excel

我试图在UserForm中的ComboBox中选择一个项目。我发现.Selected(index)= True代码几乎无处不在,但对我来说,它是sais:

Compile error: Method or data member not found.

我的代码:

Private Sub UserForm_Initialize()

Dim worksheetList As New ArrayList
Dim ws As Worksheet

For Each ws In ThisWorkbook.Worksheets
    worksheetList.Add ws.Name
Next ws

sourceWorksheets.List = worksheetList.toArray
destinationWorksheets.List = worksheetList.toArray

sourceWorksheets.Selected(1) = True 'Error here

End Sub

我做错了吗?我无法找到任何其他功能来设置"默认"项目

2 个答案:

答案 0 :(得分:2)

正如@Rory一直说的那样 - 使用ListIndex来选择列表控件中的项目。

这段代码会将每个工作表名称添加到列表控件中,然后选择第一个项目:

Private Sub UserForm_Initialize()

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        Me.worksheetList.AddItem ws.Name
    Next ws

    Me.worksheetList.ListIndex = 0

End Sub  

我认为OP试图使用类似于下面的代码,但这仍然需要ListIndex=0

Private Sub UserForm_Initialize()

    Dim ws As Worksheet

    With CreateObject("System.Collections.ArrayList")
        For Each ws In ThisWorkbook.Worksheets
            .Add ws.Name
        Next ws
        Me.worksheetList.List = .ToArray
    End With

    Me.worksheetList.ListIndex = 0

End Sub

编辑:代码假设列表控件名为 worksheetList

编辑2:稍有不同的版本。单击表单时,它会反转列表中的项目 它仍然是Me.worksheetList.ListIndex = 0来选择列表控件中的项目

Option Explicit

Public MyArrayList As Variant

Private Sub UserForm_Initialize()

    Dim ws As Worksheet

    Set MyArrayList = CreateObject("System.Collections.ArrayList")

    With MyArrayList
        For Each ws In ThisWorkbook.Worksheets
            .Add ws.Name
        Next ws
        .Sort
        Me.worksheetList.List = .ToArray
    End With

    Me.worksheetList.ListIndex = 0

    ''This will only work in a listbox, not a combobox.
    ''Select items in row numbers that are even (ListIndex 0,2,4, etc)
    ''MultiSelect must be 1 - fmMultiSelectMulti or 2 - fmMultiSelectExtended
    '    Dim x As Long
    '    For x = 0 To Me.worksheetlist.ListCount - 1
    '        If x Mod 2 = 0 Then
    '            Me.worksheetlist.Selected(x) = True
    '        End If
    '    Next x

End Sub

Private Sub UserForm_Click()

    With MyArrayList
        .Reverse
        Me.worksheetList.List = .ToArray
    End With

    Me.worksheetList.ListIndex = 0

End Sub

答案 1 :(得分:0)

要检查是否选择了特定元素(由索引表示),您应该像这样解决方法:

ComboBox1.Value = ComboBox1.List(i)

其中i为索引。必须这样做,因为在VBA SelectedIndex中没有像ComboBox这样的属性。

请记住,索引从0开始!