Friday, March 21, 2014

How to write a For Next Loop in Excel VBA ?

Below is the simple code for, loop used to give a pop-up message for numbers 1 to 10


Sub ForLoop()

For n = 1 To 10
    MsgBox n
Next

End Sub





How does this work?


Sub ForLoop()      ' Declaring Name of the Macro

For n = 1 To 10    ' Setting the variable and assigning the values to run the loop

    MsgBox n        ' Message box pop-up showing the value assigned to the variable













Next                  ' Next will take us to the Msgbox step, as the value of n is not yet 10


End Sub              ' End of the macro once the value of n is set to 10




Actual Screenshot of Code written in Excel VBA




Find Even Odd number using For Next Loop

below code is used to find the Even or Odd number:

Sub EvenOdd()
For n = 1 To 10
        If n Mod 2 = 0 Then
        MsgBox n & " is Even Number"
       Else
        MsgBox n & " is Odd Number"
    End If
Next n
End Sub



How does this work ?

' Declaring Name of the Macro
Sub EvenOdd()   

' Setting the variable and assigning the values to run the loop
For n = 1 To 10
    
' Here we are checking the simple logic of Math's, using which we are checking if the number is divisible by 2. If the result of modulus is 0 it means that number can be divided by 2 and is Even Number. Similarly if the modulus is not exactly 0, this means the number is not exactly divisible by 2, hence it will be Odd number.
    If n Mod 2 = 0 Then
    
'If modulus output is 0
    MsgBox n & " is Even Number"
    



    Else
  
'If modulus output is not exactly zero  
    MsgBox n & " is Odd Number"



'End of If Statement
    End If

' Next will take us to the Msgbox step, as the value of n is not yet 10
Next n           

' End of the macro once the value of n is set to 10

End Sub


Actual screenshot of the Excel VBA code:

No comments:

Post a Comment