将数组与标量乘以添加VBA



我在excel表中有两列数据,它们的大小相等,两者都包含数字。

我正在尝试编写一个将这两个集合放入数组中的宏,然后对它们进行计算。特异性ArrayA + 3*ArrayB然后将结果放回新列中的工作表中。以下是我到目前为止的代码。

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

您需要首先制作一个值。然后确保您将hroup hroup hroup 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

Note 未经测试的上述代码,因此我可能在其中有一个错别字。另外,您可能需要在使用Redim时声明Arrayc的数据类型,而不是变体。目前,我无法通过手机回答。

最新更新