【发布时间】:2021-07-20 22:06:51
【问题描述】:
我想要一个 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
这段代码有什么问题?!如果可以,请帮助我。
【问题讨论】:
-
你的:
ReDim Arr2(LB2 To UB2, 1 To 1)应该在 IF 之前。现在它只有在ElmToRemoveIndex < LB1 Or ElmToRemoveIndex > UB1时才会重新调暗 -
顺便说一句:
Dim UB1, LB1, UB2, LB2 As Long仅将LB2声明为Long其他都是Variant而且Fors 只需要像:For i = LB1 To UB2 -
嗨。你说得对 。谢谢。