您需要先製作一組數值。然後確定你已經完成陣列了。
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
注意上面的代碼是未經測試,所以我可以有它的一個錯字的地方。另外,在使用redim時,您可能需要聲明ArrayC的數據類型而不是變體。目前我無法測試,因爲我正在用手機接聽電話。
你能發佈錯誤信息嗎?我也想知道是否需要執行工作表(「Sheet1」)。範圍(「A1:A5」)。值指定範圍的值 – SheldonH
您不能乘以VBA中的數組。你只是想爲陣列A和B中的每對值計算C = A + 3B?如果是這樣,那麼你需要遍歷數組並執行該計算。 –