my understanding is that this Merge function takes two arrays (arr1 and arr2) as inputs and returns a new array that merges the elements of both arrays in an alternating fashion. If one array is longer than the other, the remaining elements of the longer array are appended at the end.
Function Merge(ByVal arr1 As Variant, ByVal arr2 As Variant) As Variant
Declares a function named Merge that takes two arguments (arr1 and arr2) of type Variant.
The function returns a Variant because arrays in VBA are typically handled as Variant.
Dim tmpArr As Variant, upper1 As Long, upper2 As Long
Dim higherUpper As Long, i As Long, newIndex As Long
Declares:
tmpArr: A temporary array that will hold the merged result.
upper1: Stores the upper bound (size) of arr1.
upper2: Stores the upper bound (size) of arr2.
higherUpper: Stores the greater of upper1 and upper2, used to control the loop.
i: Loop counter.
newIndex: Tracks the position where the next element should be inserted in tmpArr.
upper1 = UBound(arr1) + 1
upper2 = UBound(arr2) + 1
UBound(arr1) gives the highest index of arr1, so adding 1 gives the total number of elements.
Same logic applies for arr2.
higherUpper = IIf(upper1 >= upper2, upper1, upper2)
Uses IIf (immediate if) to determine the larger size between upper1 and upper2.
ReDim tmpArr(upper1 + upper2 - 1)
Allocates space for tmpArr with a size equal to the total number of elements in both arrays.
Loops from 0 to higherUpper.
higherUpper ensures we iterate enough times to include all elements of both arrays.
If i < upper1 Then
tmpArr(newIndex) = arr1(i)
newIndex = newIndex + 1
End If
If i is within the bounds of arr1, insert arr1(i) into tmpArr at newIndex and increment newIndex.
If i < upper2 Then
tmpArr(newIndex) = arr2(i)
newIndex = newIndex + 1
End If
Similarly, if i is within the bounds of arr2, insert arr2(i) into tmpArr at newIndex and increment newIndex.
Moves to the next iteration in the loop.
Assigns the merged array (tmpArr) to the function output.
So its like if you had a casino dealer that was perfect at shuffling cards on the table by lifting the edge of the cards and alternating them together but one half of the deck was larger, you would end up with them being alternated but with the remaining cards ending up at the bottom.