Multiplying arrays with scalars and adding to VBA

I have two columns of data in an excel sheet that are equal in size and both contain only numbers.

I am trying to write macros that put both of these sets into arrays and then do calculations on them. In particular, ArrayA + 3*ArrayBthen return the result to the worksheet in a new column. Below is the code that I have.

Dim ArrayA As Variant
Dim ArrayB As Variant
Dim ArrayC As Variant

ArrayA = Worksheets("Sheet1").Range("A1:A5")
ArrayB = Worksheets("Sheet1").Range("B1:B5")

'this is where things go bad
ArrayC = ArrayA + 3 * ArrayB
+2
source share
1 answer

You need to create an array of values ​​first. Then make sure you eloit the arrays.

Dim ArrayA As Variant
Dim ArrayB As Variant
Dim ArrayC() As Variant

ArrayA = Worksheets("Sheet1").Range("A1:A5").Value
ArrayB = Worksheets("Sheet1").Range("B1:B5").Value

'this is where things go bad
'ArrayC = ArrayA + 3 * ArrayB

'manually make array C the same size as array A
ReDim ArrayC(LBound(ArrayA, 1) To UBound(ArrayA, 1), 1 To 1)

Dim i As Long 'variable to count which section of the array we are on

' loop through each spot int he array and perform the math
For i = LBound(ArrayA, 1) To UBound(ArrayA, 1)
    ArrayC(i, 1) = ArrayA(i, 1) + 3 * ArrayB(i, 1)
Next i

Worksheets("Sheet1").Range("C1:C5").Value = ArrayC

, -. , ArrayC redim. , .

+3

All Articles