VBA阵列不';不行?

VBA阵列不';不行?,vba,excel,Vba,Excel,我有5个订单价格的实践文件。目标是向每个记录中添加20美元,并有一个消息框来显示结果 以下是数据: 我的代码是: Sub TotalDelivery() Dim curDelCharge As Currency Dim curTotal(4) Dim i As Integer Worksheets("Sheet1").Range("B10").Activate Const curDelCharge = 20 For i = 0 To 4 curTotal(i) = ActiveCel

我有5个订单价格的实践文件。目标是向每个记录中添加20美元,并有一个消息框来显示结果

以下是数据:

我的代码是:

Sub TotalDelivery()
Dim curDelCharge As Currency
Dim curTotal(4)

Dim i As Integer

Worksheets("Sheet1").Range("B10").Activate

Const curDelCharge = 20

For i = 0 To 4

curTotal(i) = ActiveCell.Offset(i, 1).Value + curDelCharge

MsgBox (curTotal(i))

Next i
End Sub
但是,消息框仅显示20,这只是我的curDelCharge值

要进行调试,我将msgbox代码更改为: MsgBox(ActiveCell.Offset(i,1.Value)

返回值为空,这意味着代码不读取我的ActiveCell值。为什么呢

提前谢谢

这一行:

curTotal(i) = ActiveCell.Offset(i, 1).Value + curDelCharge
应改为:

curTotal(i) = ActiveCell.Offset(i, 0).Value + curDelCharge

放置“1”将向右移动偏移量1列,这是您不希望的。

并且有一些指针指示如何避免使用
Select
activate
。或者类似
MsgBox[sum(B10:B14)+20]
是的,我应该使用(I,0)而不是(I,1)。谢谢!
Sub TotalDelivery()
Dim curTotal(4)
Dim i As Integer
Dim rngCellsToChange As Range 'range of cells you are targeting
Dim rCell As Range 'individual cell in collection of cells. See alternative solution below

'You can refer to cells directly, without activating them.
'You are highly discouraged to use Activate or Select methods.
'Use ThisWorkbook to explicitly tell VBA, which workbook you are targeting
Set rngCellsToChange = ThisWorkbook.Worksheets("Sheet1").Range("B10:B14")

Const curDelCharge = 20

For i = 0 To 4
    curTotal(i) = rngCellsToChange(i + 1).Value + curDelCharge
    MsgBox (curTotal(i))
Next i

'Alternatively, you can use the Range object to loop through all it's cells, like so:
For Each rCell In rngCellsToChange
    MsgBox rCell.Value + curDelCharge
Next

End Sub