arrays - 根据索引从数组中删除一个元素(vba)
问题描述
我想要一个 vba 函数,它需要一个 2D(1 到 n,1 到 1)数组和一个索引,并从数组中删除一个元素(基于该索引)。我编码如下:
'this function removes an element of a 2D(1 to n,1 to 1) array based on the input index
Function RemoveElementFromArray(Arr1, Index As Long)
Dim Arr2
Dim i, ElmToRemoveIndex As Long
Dim UB1, LB1, UB2, LB2 As Long
ElmToRemoveIndex = Index
LB1 = LBound(Arr1): UB1 = UBound(Arr1)
LB2 = LB1: UB2 = UB1 - 1
If ElmToRemoveIndex < LB1 Or ElmToRemoveIndex > UB1 Then
MsgBox "The index is out of range!", vbExclamation
ReDim Arr2(LB2 To UB2, 1 To 1)
ElseIf ElmToRemoveIndex = LB1 Then
For i = LB1 To i = UB2
Arr2(i, 1) = Arr1(i + 1, 1)
Next
ElseIf ElmToRemoveIndex > LB1 And ElmToRemoveIndex < UB1 Then
For i = LB1 To i = ElmToRemoveIndex - 1
Arr2(i, 1) = Arr1(i, 1)
Next
For i = ElmToRemoveIndex To i = UB2
Arr2(i, 1) = Arr1(i + 1, 1)
Next
ElseIf ElmToRemoveIndex = UB2 Then
For i = LB1 To i = UB2
Arr2(i, 1) = Arr1(i, 1)
Next
End If
RemoveElementFromArray = Arr2
End Function
但是当我尝试在 sub 中使用它时遇到了运行时错误“13”:类型不匹配,而我希望打印“saeed”!
Sub test()
Dim Arr1(1 To 5, 1 To 1)
Dim Arr2
Dim ElmToRemoveIndex As Long
Arr1(1, 1) = "ali"
Arr1(2, 1) = "reza"
Arr1(3, 1) = "ahmad"
Arr1(4, 1) = "saeed"
Arr1(5, 1) = "shah"
ElmToRemoveIndex = 3
Arr2 = RemoveElementFromArray(Arr1, ElmToRemoveIndex)
Debug.Print Arr2(3, 1)
End Sub
这段代码有什么问题?!如果可以,请你帮助我。
解决方案
如评论中所述,我们需要在 IF 之外重新调整新数组。
多个 If 也可以用计数器替换:
Function RemoveElementFromArray(Arr1 As Variant, Index As Long)
Dim UB1 As Long
UB1 = UBound(Arr1, 1)
Dim LB1 As Long
LB1 = LBound(Arr1, 1)
Dim Arr2() As Variant
ReDim Arr2(LB1 To UB1 - 1, 1 To 1)
If Index < LB1 Or Index > UB1 Then
MsgBox "The index is out of range!", vbExclamation
Else
Dim k As Long
k = LB1
Dim i As Long
For i = LB1 To UB1 - 1
If i <> Index Then
Arr2(k, 1) = Arr1(i, 1)
k = k + 1
End If
Next i
End If
RemoveElementFromArray = Arr2
End Function
推荐阅读
- macos - mac终端路径中的faroarm-laptop是什么?我的用户名@faroarm-laptop ~ %
- azure - 我可以使用 Azure Policy 来审核或强制执行 Azure 活动日志诊断设置吗?
- css - 使用 CSS 在下拉菜单中更改照片
- java - java数组字节文件到人类可读
- typescript - 为什么我收到 NoExplicitTypeError?
- reactjs - 如何从 React 上下文中只导入我需要的函数
- c# - 如何检查数据库中是否存在特定字段,如果不存在则添加记录,否则进行编辑
- tensorflow - Keras `ImageDataGenerator` 图像和蒙版的增强方式不同
- python - Django - calling function does not redirect
- python - 如何将信息从 GUI 发送到 Excel 电子表格?下面是我的代码