arrays - Excel VBA 数组:有没有一种简单的方法可以按索引删除数据集?
问题描述
是否有一种简单的方法可以通过索引从数组中删除特定数据集?
例子:
Dim array() as string
ReDim array(2,2)
array(0,0) = "abc"
array(0,1) = "Peter"
array(0,2) = "New York"
array(1,0) = "xyz"
array(1,1) = "Bob"
array(1,2) = "Los Angeles"
array(2,0) = "klm" ' edited (enumeration error in OP)
array(2,1) = "Stacey"
array(2,2) = "Seattle"
所以我的数组显示在
0: abc, Peter,New York
1: xyz, Bob, Los Angeles
2: klm, Stacey, Seattle
我现在从之前的计算中知道我不再需要索引 1的 Bob ,我想删除他的记录
有没有像下面这样简单的东西?
ReDim Preserve array(UBound(array) - 1)
array.delete(1)
解决方案
试试这个一维数组
Sub test()
Dim strr As String
strr = "0|1|2|3|5"
wArr = Split(strr, "|")
d = DeleteElementAt(2, strr)
End Sub
Function DeleteElementAt(ByVal index As Integer, ByRef prLsts, strDelimeter) As String
Dim i As Integer
Dim newLst
' Move all element back one position
prLst = Split(prLsts, strDelimeter)
If UBound(prLst) > 0 Then
ReDim newLst(UBound(prLst) - 1)
For i = 0 To UBound(prLst)
If i <> index Then newLst(y) = prLst(i): y = y + 1
Next
DeleteElementAt = Join(newLst, strDelimeter)
Else
DeleteElementAt = prLsts
End If
End Function
对于二维数组
Function Delete2dElementAt(ByVal index As Integer, ByRef prLsts) As Variant
Dim i As Integer
Dim newLst
' Move all element back one position
prLst = prLsts
If index > UBound(prLst) Then MsgBox "overcome index": Exit Function
If UBound(prLst) > 0 Then
ReDim newLst(UBound(prLst) - 1, UBound(prLst, 2))
For i = 0 To UBound(prLst)
If i <> index Then
For Z = LBound(prLst, 2) To UBound(prLst, 2)
newLst(y, Z) = prLst(i, Z)
Next Z
y = y + 1
End If
Next
Delete2dElementAt = newLst
Else
Delete2dElementAt = prLsts
End If
End Function
推荐阅读
- nginx - Openresty:如何使用不同的 nginx.conf?
- php - PHP Echo ipv4 和 IPv6
- java - 无法在 VSCode 终端中运行 java
- python - OSError running python script 说明 DLL libjli.dylib 实际存在时找不到
- java - discord4j 的错误符号引用
- extjs - 我正在尝试增加 extjs 中网格列标题的边框权重,但它不会增加超过 1px 有没有其他方法可以增加?
- visual-studio-code - VSCode:使用正则表达式查找和替换并保留周围的上下文(未捕获的部分)
- python - FastAPI - 向 TestClient 添加路由前缀
- jsf - JSF 2.3 使用来自休息服务的@PushContext
- flutter - 如何使用 MongoDB 数据库实现 Google Sign in Flutter 应用