adding arrays - generic method

elmonkfish
05-10-2010, 02:24 AM
I have created a function that will add two user defined type arrays together (see below). And now I want to do the same for a number of other user defined types (and also string/integer/double etc) but don't want to have to create duplicate functions; ideally I want one "AddArrays" function that will take any two arrays (of the same type) and add them together. The problem is if I change the parameters being passed in to be Variants I get a complile error (Type mismatch: array or user-defined type expected). Is it possible to do this or am I just going to have create lots of duplicate functions for each variable type?


Public Function AddArrays(uaArray1() As udtMyType, _
uaArray2() As udtMyType) As udtMyType()

Dim uaArray3() As udtMyType
Dim nLB1 As Integer
Dim nUB1 As Integer
Dim nLB2 As Integer
Dim nUB2 As Integer
Dim nLoop As Integer
Dim nLoop2 As Integer
Dim bArray1Error As Boolean
Dim bArray2Error As Boolean

bArray1Error = False
bArray2Error = False

' attempt to set lower and upper bounds
On Error GoTo Array1Error
nLB1 = LBound(uaArray1)
nUB1 = UBound(uaArray1)
On Error GoTo Array2Error
nLB2 = LBound(uaArray2)
nUB2 = UBound(uaArray2)
GoTo DoAddition

Array1Error:
bArray1Error = True
On Error GoTo ExitFunc
nLB2 = LBound(uaArray2)
nUB2 = UBound(uaArray2)
nUB1 = -1 ' -1 to correct the +1 in array 3 redim as array 1 is empty
GoTo DoAddition

Array2Error:
bArray2Error = True

DoAddition:

ReDim uaArray3(0 To (nLB1 + nUB1 + nLB2 + nUB2 + 1))

nLoop = 0
For nLoop2 = nLB1 To nUB1
If bArray1Error = False Then
uaArray3(nLoop) = uaArray1(nLoop2)
nLoop = nLoop + 1
End If
Next nLoop2
For nLoop2 = nLB2 To nUB2
If bArray2Error = False Then
uaArray3(nLoop) = uaArray2(nLoop2)
nLoop = nLoop + 1
End If
Next nLoop2

ExitFunc:

AddArrays = uaArray3

End Function

Flyguy
05-10-2010, 03:27 AM
Using Variants you can create a generic function, I haven't tested it for UDT arrays

Private Sub Form_Load()
Dim i As Long
Dim l1() As Long, l2() As Long, l3() As Long
Dim s1() As String, s2() As String, s3() As String
Dim v As Variant

ReDim l1(3)
ReDim l2(2)
l1(0) = 0: l1(1) = 1: l1(2) = 2: l1(3) = 3
l2(0) = 4: l2(1) = 5: l2(2) = 6

v = JoinArrays(l1, l2)
For i = 0 To UBound(v)
Debug.Print i, v(i)
Next i

ReDim s1(2)
ReDim s2(1)

s1(0) = "A": s1(1) = "B": s1(2) = "C"
s2(0) = "D": s2(1) = "E"

v = JoinArrays(s1, s2)
For i = 0 To UBound(v)
Debug.Print i, v(i)
Next i


End Sub

Public Function JoinArrays(a1 As Variant, a2 As Variant) As Variant
Dim a3 As Variant
Dim i As Long

ReDim a3(UBound(a1) + UBound(a2) + 1)

For i = 0 To UBound(a1)
a3(i) = a1(i)
Next i

For i = 0 To UBound(a2)
a3(UBound(a1) + 1 + i) = a2(i)
Next i

JoinArrays = a3
End Function

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum