Simple Procedure call close to your post, but returning a 1-based array
Using the advanced possibilities of the Application.Index
function I demonstrate an approach close to your wanted pseudo-method array.delete(1)
in OP:
delArr arr, 2 ' see section [1] in the Example call below
where
delArr
is the calling procedure,
arr
is the array name (don't use a reserved function's name to baptize your array!) and
2
is the element row number as Application.Index
returns only 1-based arrays.
Example call
Sub DelGivenElementNumber()
Dim arr() As Variant, i As Long
ReDim arr(1 To 3, 1 To 3) ' redimension to 1-based array :-)
arr(1, 1) = "abc": arr(1, 2) = "Peter": arr(1, 3) = "New York"
arr(2, 1) = "xyz": arr(2, 2) = "Bob": arr(2, 3) = "Los Angeles"
arr(3, 1) = "klm": arr(3, 2) = "Stacey": arr(3, 3) = "Seattle"
' --------------------------------
' [1] delete element row number 2 ' i.e. xyz|Bob|Los Angeles
' --------------------------------
delArr arr, 2
' [2] optionally: check remaining element rows (now 1-based!)
For i = LBound(arr) To UBound(arr)
Debug.Print i, dispArrElements(arr, i)
Next i
End Sub
Result of the restructured 1-based array in the VBE's immediate window:
1 abc, Peter, New York
2 klm , Stacey, Seattle
Main procedure delArr
The main procedure delArr
is only a one liner and has only two arguments:
- the data array itself passed by reference and
- the 'row' number to be deleted (1-based, e.g. 2 represents the second element row):
Sub delArr(arr, r As Long)
arr = Application.Index(arr, validRows(arr, r), allCols(UBound(arr, 2)))
End Sub
Helper functions
The main procedure uses two helper functions to get arrays with the remaining row numbers and column numbers (here: Array(1,2,3)
for e.g. three columns).
Function validRows(arr, ByVal n&) As Variant()
' Purpose: get 0-based 1-dim Array(1,3), i.e. all remaining original row numbers counting from 1, omitting 2
Dim i&, nRows&
nRows = UBound(arr) - LBound(arr) + 1 ' original row number
ReDim tmp(0 To nRows - 2) ' zero-based tmp counter: -1, omitting element n: -1 ~~> -2
For i = 1 To n - 1 ' collect elements before element n
tmp(i - 1) = i
Next i
For i = n To nRows - 1 ' collect elements after element n
tmp(i - 1) = i + 1 ' count old row numbers, but with reduced tmp counter
Next i
' Debug.Print Join(tmp, "|")
validRows = Application.Transpose(tmp) ' return array of found row numbers
End Function
Function allCols(ByVal n&) As Variant()
' Purpose: get 0-based 1-dim Array(1,2,... n), i.e. all column numbers
allCols = Application.Transpose(Evaluate("row(1:" & n & ")"))
End Function
Optional function to display results
Uses the Join
function to display one row element with all three columns of your example (see section [2]
in the example call):
Function dispArrElements(arr, r As Long) As String
dispArrElements = Join(Application.Transpose(Application.Transpose(Application.Index(arr, r, 0))), ", ")
End Function