There is no innate functionality that gives this unfortunately.
What you can do is track the listbox selection in an array by modifying
an array every time the listbox is changed. Here's an example of how to
do this. (It could all be done in the change event of course but I
decided to reuse some existing functions I had knocking around.)
To get the last selection made you simple use
mySelection(ubound(myselection)). If that is deselected then
mySelection(ubound(myselection)) still gets you the one before that.
I've used Caption1 and ListBox1 on my userform
Option Explicit
Private mySelection() As Integer
Private Sub UserForm_Initialize()
With ListBox1
.AddItem "Monkey"
.AddItem "Hippo"
.AddItem "Giraffe"
.AddItem "Cat"
.AddItem "Emu"
End With
End Sub
Private Sub ListBox1_Change()
Dim idx As Integer, i As Integer
'go through the ListBox and compare what's selected
'with what's in our array
With ListBox1
For i = 0 To .ListCount - 1
'is this item in our array?
idx = fcnArrayFindIndex(mySelection, i)
If idx > -1 Then
If Not .Selected(i) Then
DeleteItemFromArray mySelection, idx
Exit For 'there'll only be one change at once
End If
Else 'it's not in the array
If .Selected(i) Then
'add it to our array
fcnArrayAddItemTo mySelection, i
Exit For 'there'll only be one change at once
End If
End If
Next i
End With
'display our results
Label1.Caption = Empty
If fcnIsInitialisedArray(mySelection) Then
For i = 0 To UBound(mySelection)
Label1.Caption = Label1.Caption & mySelection(i) & vbCrLf
Next i
End If
End Sub
Public DeleteItemFromArray(ByRef arr() As Integer, idx As Integer)
If UBound(arr) = 0 Then
Erase arr
ElseIf idx = UBound(arr) Then
ReDim Preserve arr(idx - 1)
Else
Dim newarr() As Integer
Dim i As Integer, iNew As Integer
ReDim newarr(UBound(arr) - 1)
For i = 0 To UBound(arr)
If i <> idx Then
newarr(iNew) = arr(i)
iNew = iNew + 1
End If
Next i
arr = newarr
End If
End Sub
'Finds an item in an array
Public Function fcnArrayFindIndex(ByRef myArray() As Integer, myValue As
Variant) As Integer
Dim i As Integer
If fcnIsInitialisedArray(myArray) Then
For i = LBound(myArray) To UBound(myArray)
If CStr(myArray(i)) = CStr(myValue) Then
fcnArrayFindIndex = i
Exit Function
End If
Next i
End If
fcnArrayFindIndex = -1
End Function
'Adds an item to a passed array
Public Function fcnArrayAddItemTo(ByRef myArray() As Integer, myValue As
Variant) As Boolean
On Error GoTo ErrorHandler
If Not fcnIsInitialisedArray(myArray) Then
ReDim myArray(0)
myArray(0) = myValue
Else
ReDim Preserve myArray(UBound(myArray) + 1)
myArray(UBound(myArray)) = myValue
End If
fcnArrayAddItemTo = True
ErrorHandler:
On Error GoTo 0
End Function
Function fcnIsInitialisedArray(ByRef arr() As Integer) As Boolean
If IsArray(arr) Then
On Error Resume Next
If UBound(arr) < 0 Then
Else
fcnIsInitialisedArray = True
End If
End If