Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA For...Next

Tags:

excel

vba

I'm a VBA newcomer. I wonder why does sum1() show 10 while sum2() show 11? Thanks in advance.

Sub sum1()
  Dim x As Integer
  x = 0
  For x = 5 To 5
      x = x + x
      MsgBox x
  Next 
End Sub

Sub sum2()
  Dim x As Integer
  x = 0
  For x = 5 To 5
      x = x + x
  Next
  MsgBox x
End Sub
like image 387
user7433793 Avatar asked Apr 21 '26 13:04

user7433793


2 Answers

A vba for-loop increments the index variable at the end of each iteration. That is what the Next keyword does. In sum1() You get:

Sub sum1()
  Dim x As Integer
  x = 0 ' x is 0
  For x = 5 To 5 ' x  set to 5
     x = x + x 'x gets 5+5=10
  Next 'x gets 10+1=11
  MsgBox x 'display x=11
End Sub

but in sum2() you get:

Sub sum2()
  Dim x As Integer
  x = 0 ' x is 0
  For x = 5 To 5 ' x  is 5
     x = x + x 'x gets 5+5=10
     MsgBox x 'display x=10
  Next 'x gets 10+1 and is now 11
End Sub

I agree with @MitchWheat, it usually not good practice to modify your index variable while inside a loop. A better approach would be this:

Sub sum3()
    Dim x as Integer
    Dim i as Integer
    x= 1
    For i = 5 To 5
      x = x + x
    Next
    MsgBox x
End Sub
like image 88
Austin Avatar answered Apr 23 '26 06:04

Austin


For loops increment the loop variable at the end of the loop.

In the second code snippet, the for loop increments x from 10 to 11, and then you display it.

Whereas the first code snippets increments x AFTER you display it. This is not something specific to VBA.

To see this, run:

Sub sum1_1()
  Dim x As Integer

  x = 0
  For x = 5 To 5
      x = x + x
      MsgBox x
  Next 

  MsgBox x
End Sub

As an aside: It's not best practice to modify loop counters from inside a loop. It can lead to code that is hard to understand.

like image 37
Mitch Wheat Avatar answered Apr 23 '26 06:04

Mitch Wheat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!