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
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