Home » excel » vba – .Selected command form Excel

vba – .Selected command form Excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to generate ListBoxes on a spreadsheet allowing transfer of elements between them. One of the procedures, transferring elements from, say List Box 2 to List Box 3 is currently as follows:

Dim i As Long


For i = 0 To ActiveSheet.ListBoxes("List Box 2").ListCount - 1
  If ActiveSheet.ListBoxes("List Box 2").Selected(i) Then
     ActiveSheet.ListBoxes("ListBox3").AddItem ActiveSheet.ListBoxes("List Box 2").List(i)
  End If
Next i

For i = ActiveSheet.ListBoxes("List Box 2").ListCount - 1 To 0 Step -1
   If ActiveSheet.ListBoxes("List Box 2").Selected(i) Then
      ActiveSheet.ListBoxes("List Box 2").RemoveItem i
   End If
Next i

I am getting Run-time error ‘1004’: Unable to get Selected property of ListBox class. Any ideas on the error’s source?

Btw, I should clarify that I am NOT using ActiveX.

Thanks!

How to&Answers:

There is no 0 index for form listbox.selected (note active x listbox forms DO start with 0 index)

Also i was getting errors with your transfer method and so adjusted. This works.

Have to initalize i = 1

With ws.ListBoxes("List Box 2")
    For i = 1 To .ListCount
        If .Selected(i) Then
            ActiveSheet.ListBoxes("List Box 3").AddItem .List(i)
        End If
    Next i

also on the back end

For i = .ListCount To 1 Step -1
        If .Selected(i) Then
            .RemoveItem i
        End If
    Next i