2016-10-13 91 views
2

我有5個訂單價格這個練習文件。目標是爲每條記錄添加20美元,並有一個消息框顯示結果。VBA陣列不起作用?

下面是數據:

enter image description here

我的代碼是這樣的:

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(1,1).value的)

返回值是空白,這意味着該代碼不讀我的ActiveCell值。這是爲什麼?

在此先感謝!

+1

[這裏](http://stackoverflow.com/documentation/excel-vba/1107/vba-best-practices/9292/avoid-using-select-or-activate)和[這裏](HTTP ://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros)是一些指針如何避免使用「選擇」和「激活」。 – arcadeprecinct

+0

或只是像'MsgBox [sum(B10:B14)+20]' – Slai

回答

3

這條線:

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

應改爲:

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

把一個 「1」,將偏移1列向右移動,你不想要的。

+0

是的,我應該有(我,0),而不是(我,1)。謝謝! – vivi11130704

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