I have a userform with 2 listboxs (listbox1 & listbox2) that can exchange items through an 'Add' & 'Remove' buttons. Note that listbox1 is initialized from a range in excel while listbox2 is empty at first.
I tried adding two functions 'SaveItems()' and 'LoadSavedItems()' so that after closing the userform, upon reopening my listbox get populated with last saved values.
Here is the code I wrote:
Private Sub SaveItems()
Dim i As Long
If ListBox1.ListCount <> 0 Then
ReDim saveditems_lstbox1(ListBox1.ListCount - 1)
For i = 0 To ListBox1.ListCount - 1
saveditems_lstbox1(i) = ListBox1.List(i)
Next i
End If
If ListBox2.ListCount <> 0 Then
ReDim saveditems_lstbox2(ListBox2.ListCount - 1)
For i = 0 To ListBox2.ListCount - 1
saveditems_lstbox2(i) = ListBox2.List(i)
Next i
End If
End Sub
Private Sub LoadSavedItems()
Dim i As Long
'If Not IsEmpty(saveditems_lstbox1) Then
If Not UBound(saveditems_lstbox1) - LBound(saveditems_lstbox1) + 1 = 0 Then
ListBox1.Clear
For i = LBound(saveditems_lstbox1) To UBound(saveditems_lstbox1)
ListBox1.AddItem saveditems_lstbox1(i)
Next i
End If
'If Not IsEmpty(saveditems_lstbox2) Then
If Not UBound(saveditems_lstbox2) - LBound(saveditems_lstbox2) + 1 = 0 Then
ListBox2.Clear
For i = LBound(saveditems_lstbox2) To UBound(saveditems_lstbox2)
ListBox2.AddItem saveditems_lstbox2(i)
Next i
End If
End Sub
Private Sub UserForm_Initialize()
'MsgBox "Bound 1: " & UBound(saveditems_lstbox1) # I get outbound error in this msgbox
If Not UBound(saveditems_lstbox2) - LBound(saveditems_lstbox2) + 1 = 0 Then
LoadSavedItems
Else
Dim Arr
Dim last_row_B As Long
last_row_B = Cells(Rows.Count, "B").End(xlUp).Row
Arr = Range("B" & 32 & ":B" & last_row_B)
ListBox1.List() = Arr
End If
End Sub
Problem: If I initialize the variant 'Saveditems_lstbox1 & 2' inside the UserForm_Initialize() function, I erase the saved values ... If I don't initialize them I get an out of bound error !
Edit: After trying this code below, it said that arrays weren't initialized
Public Function IsArrayInitialized(arr() As Variant) As Boolean
On Error Resume Next
Dim dummy As Variant
dummy = arr(LBound(arr))
IsArrayInitialized = (Err.Number = 0)
On Error GoTo 0
End Function
Any hint or clue will be appreciated, thank you !