我需要在VB中添加和删除数组末尾的元素。
在Java中,如果我有两个方法(向数组添加元素的方法和从数组中删除元素的方法),我将通过创建静态全局变量来完成此操作。每次我调用add方法时,我只是插入然后将一个添加到位置静态变量,然后如果我需要删除一些东西,我会得到该变量,然后从中减去一个。这就是我如何将一个元素添加到数组的末尾并删除数组中的最后一个元素。您能否以相同的方式在VB中解决此问题?我对VB不太熟悉,所以语法让我失望。任何帮助将不胜感激。
答案 0 :(得分:0)
除非您可以使用Collection
对象,否则没有内置或直接的方法来执行此操作。
Public Sub TestArr()
Dim list As New Collection
list.Add "John"
list.Add "Mary"
list.Add "Bob"
list.Remove 1
End Sub
使用数组,您可以使用ReDim
关键字Preserve
来保留现有数据。
Public Sub TestArr()
Dim list() As Variant
'Creates a dynamic list of 10 items
ReDim list(1 To 10)
Dim i As Long
For i = 1 To 10
list(i) = "Item" & CStr(i)
Next i
'Append to the end of an array
AppendToArray list, "NotAnItem"
'Remove the 5th element
RemoveFromArray list, 5
End Sub
Public Sub AppendToArray(ByRef list() As Variant, ByVal item As Variant)
Dim n As Long
n = UBound(list)
' Make Room
ReDim Preserve list(1 To n + 1)
' Assign new value
list(n + 1) = item
End Sub
Public Sub RemoveFromArray(ByRef list() As Variant, ByVal index As Long)
Dim n As Long, i As Long
n = UBound(list)
' Move last items down by one
For i = index To n - 1
list(i) = list(i + 1)
Next i
ReDim Preserve list(1 To n - 1)
End Sub