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 saveditems_lstbox1() as Variant
Private saveditems_lstbox2() as Variant
Private Sub SaveItems()
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
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
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()
If IsEmpty(saveditems_lstbox1) Then
Dim Arr
Dim last_row_A As Long
last_row_B = Cells(Rows.Count, "B").End(xlUp).Row
Arr = Range("A" & 1 & ":A" & last_row_A)
ListBox1.List() = Arr
Else
LoadSavedItems
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: I tried the code below to see if my 'SavedItems_lstbox1' is initialized and it returned False !
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 !