I want a vba function that takes an 2D(1 to n,1 to 1) array and an Index and remove an element(based on that index) from the array. I coded as follows:
'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
but when I tried to use it in a sub I encountered a run-time error '13': Type mismatch, while I expected to get "saeed" printed!
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
What's the problem of this code?! please help me if you can.
ReDim Arr2(LB2 To UB2, 1 To 1)should be before the IF. Right now it only gets ReDimmed whenElmToRemoveIndex < LB1 Or ElmToRemoveIndex > UB1Dim UB1, LB1, UB2, LB2 As Longonly declaresLB2as aLongthe others are allVariantAlso theFors need only be like:For i = LB1 To UB2