akhmadsabri
New Member
- Joined
- Jun 14, 2016
- Messages
- 3
Hi guys,
So I am new to VBA.
I created a function to add 2 arrays and return a new array with added values.
I count the length of the arrays and resize the new array to the size of the passed arrays.
However I got subscript out of range error on the line "addedArray(k) = array1(k) + array2(k)"
When I hover over k and myCount1, it shows both = 4.
I even tried to resize addedArray to myCount+1 bit still get the same error.
Can anyone please help me understand why I got the error?
Here is the code full code:
Option Base 1
Dim emailAddress As String
Dim addedArray As Variant
Dim value3 As String
Dim myCount1 As Integer
Dim myCount2 As Integer
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim size As Integer
Function addProducts(array1 As Variant, array2 As Variant)
'Count element of array1
myCount1 = 1
For i = LBound(array1) To UBound(array1)
myCount1 = myCount1 + 1
Next
'Count element of array2
myCount2 = 1
For j = LBound(array1) To UBound(array1)
myCount2 = myCount2 + 1
Next
'added values of array if they have the same length
If myCount1 = myCount2 Then
'resize addedArray to the size of myCount1
ReDim addedArray(myCount1)
For k = 1 To myCount1
addedArray(k) = array1(k) + array2(k)
Next
addProducts = addedArray
ElseIf myCount1 <> myCount2 Then
MsgBox ("Arrays hast to be the same lengths")
End If
End Function
So I am new to VBA.
I created a function to add 2 arrays and return a new array with added values.
I count the length of the arrays and resize the new array to the size of the passed arrays.
However I got subscript out of range error on the line "addedArray(k) = array1(k) + array2(k)"
When I hover over k and myCount1, it shows both = 4.
I even tried to resize addedArray to myCount+1 bit still get the same error.
Can anyone please help me understand why I got the error?
Here is the code full code:
Option Base 1
Dim emailAddress As String
Dim addedArray As Variant
Dim value3 As String
Dim myCount1 As Integer
Dim myCount2 As Integer
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim size As Integer
Function addProducts(array1 As Variant, array2 As Variant)
'Count element of array1
myCount1 = 1
For i = LBound(array1) To UBound(array1)
myCount1 = myCount1 + 1
Next
'Count element of array2
myCount2 = 1
For j = LBound(array1) To UBound(array1)
myCount2 = myCount2 + 1
Next
'added values of array if they have the same length
If myCount1 = myCount2 Then
'resize addedArray to the size of myCount1
ReDim addedArray(myCount1)
For k = 1 To myCount1
addedArray(k) = array1(k) + array2(k)
Next
addProducts = addedArray
ElseIf myCount1 <> myCount2 Then
MsgBox ("Arrays hast to be the same lengths")
End If
End Function