most
Board Regular
- Joined
- Feb 22, 2011
- Messages
- 107
- Office Version
- 365
- 2019
- Platform
- Windows
- Mobile
I need some help with some code I use in a form.
I have a form were the user can select columns in a sheet and hide and unhide them, that code works fine.
My challenge is that I'm trying to save selected items in the list box to an preset, which the user should be able to restore.
My solution is to store the column letters in an global array, which works fine.
The problem is that I can't get them restored, see Button_Preset2_Click.
Second problem is that I would like have the same button for saving and restoring, my solution is to do check if the preset is empty.
But none of the examples below works.
I have a form were the user can select columns in a sheet and hide and unhide them, that code works fine.
VBA Code:
Private Sub UserForm_Initialize()
lCol = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column
ListBox.ColumnCount = 2
ListBox.MultiSelect = 2 'Enables to select several values
With Me.ListBox
.ColumnWidths = "25;75"
End With
'Get all column headers name
For c = 1 To lCol
ListBox.AddItem
ListBox.List(c - 1, 0) = Split(Cells(1, c).Address, "$")(1)
ListBox.List(c - 1, 1) = Cells(1, c).value
Next c
End Sub
My challenge is that I'm trying to save selected items in the list box to an preset, which the user should be able to restore.
My solution is to store the column letters in an global array, which works fine.
The problem is that I can't get them restored, see Button_Preset2_Click.
VBA Code:
Public preset1 As Object
Private Sub Button_Preset1_Click()
Set preset1 = CreateObject("System.Collections.ArrayList")
'Add column letter of selected items to array
For i = 0 To ListBox.ListCount - 1
If ListBox.Selected(i) = True Then
preset1.Add ListBox.List(i)
End If
Next i
'Just for showing it works
For i = 0 To preset1.count - 1
Debug.Print preset1(i)
Next i
End Sub
Private Sub Button_Preset2_Click()
For a = 0 To UBound(preset1) 'Loop through all items in array
For r = 0 To ListBox.ListCount - 1 'Loop through all items in list box
If IsInArray(preset1(a), preset1) Then ListBox.Selected(r) = True 'If found select it
Next r
Next a
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
Second problem is that I would like have the same button for saving and restoring, my solution is to do check if the preset is empty.
But none of the examples below works.
VBA Code:
If Len(Join(preset1)) > 0 Then MsgBox "Preset empty!"
If IsEmpty(preset1) Then MsgBox "Preset empty!"
If IsNumeric(UBound(preset1)) = False Then MsgBox "Preset empty!"