[RESOLVED] Delete Items From Array
hi, all
I am trying to delete items but i keep getting a subscript out of range. I left my code below to see if i done something wrong.
Code:
Private Items() As String
Private RecCount As Long
Public Sub AddRecord(ByVal sRec As String)
'Resize array
ReDim Preserve Items(0 To RecCount) As String
'Store record
Items(RecCount) = sRec
'Inc record counter
RecCount = (RecCount + 1)
End Sub
Private Sub DeleteRecord(ByVal Index As Long)
Dim Counter As Long
Dim Tmp() As String
Dim idx As Long
On Error GoTo ErrFlag:
For Counter = 0 To RecCount - 1
If (Counter <> Index) Then
ReDim Preserve Tmp(0 To idx) As String
Tmp(idx) = Items(Counter)
idx = (idx + 1)
'Inc idx
End If
Next Counter
Items = Tmp
RecCount = UBound(Tmp)
Exit Sub
ErrFlag:
RecCount = 0
End Sub
Private Sub cmdDelete_Click()
Call DeleteRecord(0)
Call Command1_Click
End Sub
Private Sub Command1_Click()
Dim x As Long
'Clear listbox
Call List1.Clear
'Show items in list box
For x = 0 To UBound(Items)
Call List1.AddItem(Items(x))
Next x
End Sub
Private Sub Form_Load()
'Add some items
AddRecord "Software"
AddRecord "Games"
AddRecord "Hardware"
End Sub
Thanks
Re: Delete Items From Array
I had made some changes to it. Try it:
Code:
Option Explicit
Private Items() As String
Private RecCount As Long
Public Sub AddRecord(ByVal sRec As String)
'Inc record counter
RecCount = RecCount + 1
'Resize array
ReDim Preserve Items(RecCount) As String
'Store record
Items(RecCount) = sRec
End Sub
Private Sub DeleteRecord(ByVal Index As Long)
If RecCount = -1 Then Exit Sub '~~~> If it is empty, then prevent the rest of the code from executing
Dim Counter As Long
For Counter = Index To RecCount - 1 ' - 1
Items(Counter) = Items(Counter + 1)
Next Counter
RecCount = RecCount - 1
If RecCount <= -1 Then
Erase Items
Else
ReDim Preserve Items(RecCount)
End If
End Sub
Private Sub cmdDelete_Click()
Call DeleteRecord(0)
Call Command1_Click
End Sub
Private Sub Command1_Click()
Dim x As Long
'Clear listbox
Call List1.Clear
If RecCount = -1 Then Exit Sub '~~~> If it is empty, then prevent the rest of the code from executing
'Show items in list box
For x = 0 To UBound(Items)
Call List1.AddItem(Items(x))
Next x
End Sub
Private Sub Form_Load()
RecCount = -1 '~~~> Initialize
'Add some items
AddRecord "Software"
AddRecord "Games"
AddRecord "Hardware"
End Sub
...:wave:
Re: Delete Items From Array
Thanks akhileshbc that seems to work now.