2

I have this practice file with 5 order prices. The goal is to add $20 to each of the record and have a message box to display the result.

Here is the data:

enter image description here

My code is this:

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

However the message box only displays 20 which is only my curDelCharge value.

To debug, I change the msgbox code into: MsgBox (ActiveCell.Offset(i, 1).Value)

The return value is blank which means the code doesn't read my ActiveCell value. Why is that?

Thanks in advance!

2
  • 1
    Here and here are some pointers how to avoid using Select and activate. Commented Oct 13, 2016 at 16:36
  • or just something like MsgBox [sum(B10:B14)+20] Commented Oct 14, 2016 at 11:26

2 Answers 2

3

This line:

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

should instead be:

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

Putting a "1" will move the offset 1 column to the right, which you don't want.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I should have (i,0) instead of (i,1). Thanks!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.