Function Flatten()
with optional header cut and/or rebase action
Returns an x-based 1D array removing the header via Filter()
function and allowing to rebase to any lower boundary:
Function Flatten(rng As Range, _
Optional cutHeader As Boolean = True, _
Optional newBase As Long = 0)
'Note: assumes optional header row in a one-column range
Const DEL = "$DEL$"
'a) get a "flat" 1D array
Dim tmp: tmp = Application.Transpose(rng.Value2)
'b) remove header (optional)
If cutHeader Then tmp(LBound(tmp)) = DEL
tmp = Filter(tmp, DEL, False) ' Filter always returns a 0-based array)
'c) rebase to newBase(optional)
If newBase Then
ReDim Preserve tmp(newBase To UBound(tmp) + newBase)
End If
'd) return function result as 1D x-based array
Flatten = tmp
End Function
Example Calls
Sub ExampleCalls()
'A) Define Range
Dim rng As Range: Set rng = Tabelle1.Range("A1:A10")
'B) Example calls
Dim result As Variant
'Example 1) 1D 0-based array with header
result = Flatten(rng, False)
display result, False
'Example 2) 1D 0-based array without header
result = Flatten(rng) ' cut header (default)
display result
'Example 3) 1D 3-based array without header
result = Flatten(rng, True, 3) ' cut header explicitly AND rebase
display result
End Sub
Helper procedure Display()
Displays results in VB Editor's immediate window:
Sub display(flatArr, Optional cutHeader As Boolean)
Static cnt As Long: cnt = IIf(cnt, cnt + 1, 1)
Debug.Print cnt & ") Boundaries " & _
IIf(cutHeader, "w/o ", "with") & _
" header: (" & LBound(flatArr) & " To " & UBound(flatArr) & ")" & vbNewLine & vbTab & _
Join(flatArr, "|")
End Sub