## Thursday, April 30, 2009

### VBA, For Next loop

For next is looping method when you are definite about number of values you want to scan/test. However, you will have to use IF then to test the values. Lets take a look at very basic example of For Next loop and then we will move at little complex examples.

Syntax:

For counter = startvalue to endvalue
Operation you want to perform
Next counter
Next counter increase the value to loop till counter reaches end value

Here you want to just enter random numbers starting from active cell to next 10 row using VBA/Macro code

# For Next loop Example 1

Sub Fornextloop1()
Dim i As Integer

'We will use i as counter
For i = 0 To 9
ActiveCell.Offset(i, 0) = WorksheetFunction.RandBetween(25, 250)
Next i

End Sub

Note: Code     ActiveCell.Offset(i, 0) = WorksheetFunction.RandBetween(25, 250) may not work with MS Office 2003 or previous version. Please replace the following code with

ActiveCell.Offset(i, 0) = WorksheetFunction.Rand(25, 250)

Similary, if you want to list of 10 values of actual and 10 values of target lying in set of adjacent cells and you want to find out whether actual have exceeded the target or not.

# For Next loop Example 2

Sub Fornextloop2()
Dim i As Integer
'We will use i as counter
For i = 0 To 9
If ActiveCell.Offset(i, 0) >= ActiveCell.Offset(i, 1) Then
ActiveCell.Offset(i, 2) = "MET"
Else
ActiveCell.Offset(i, 2) = "NOT MET"
End If
Next i

End Sub

Here in the above examples we are taking increment of 1 only. In case if you want to have increment of more than 1 than you can take look at example where I have illustrated Example 1 but you only want to put even numbers. Like 2, 4, 6.... 20

# For Next loop Example 3

Sub Fornextloop3()
Dim i As Integer

'We will use i as counter
For i = 0 To 20 Step 2
ActiveCell.Offset(i / 2, 0) = i
Next i
End Sub

Step 2 makes the counter incremented by 2 each time. Also, i / 2 under offset ensures that each value in inserted in row. Only i will insert values in alternate cells.

You may think is it necessary always to increase value of counter can't we decrease the value of counter. Yes, we can do that as well. Next example illustrate the same. Now, we want to scan all the rows starting from 40th row and move to 1st row. Also, we want to highlight values above certain threshold (Here I have take 30 as threshold).

# For Next loop Example 4

Sub Fornextloop4()
Dim i As Integer
'We will use i as counter
ActiveSheet.Cells(1, 1).Select
For i = 39 To 1 Step -1
If ActiveCell.Offset(i, 0) > 30 Then
ActiveCell.Offset(i, 0).Interior.ColorIndex = 3
End If
Next i
End Sub

Step -1 decreases the value of i by 1.

Next example will shows us how to run nested For Next loop which is of extremely use full when you want to move across rows and columns at a time. I am using the example similar as previous one.

# For Next loop Example 5

Sub Fornextloop5()
Dim i As Integer
Dim j As Integer
'We will use i as counter
ActiveSheet.Cells(1, 1).Select
For i = 11 To 1 Step -1
For j = 11 To 1 Step -1
If ActiveCell.Offset(i, j) > 30 Then
ActiveCell.Offset(i, j).Interior.ColorIndex = 3
End If
Next j
Next i
End Sub

I am sure this post will help you in applying For Next Loop. In case if you find difficult to use in your MS Excel Sheet. I would suggest you download file with Example. Press Alt + F11 to view code and press Alt+ F8 to run the code.

For Next Example

Please do let me know your comments about my attempt to help beginners with For Next loop. Also, you can subscribe via email

We assure you knowledge, not SPAM!

## Wednesday, April 29, 2009

### VBA, Do while Loop, Do loop until

This is every useful VBA loop as it can be used for indefinite range with conditions applied. Like when you wanted to test starting to row 1 to last non-empty row or want to run macro for any particular condition only. You should remember that there is counter used for increment and this counter has to be part of criteria and there is Loop statement which rounds off the Do while statement. Loop is similar to Endif in IF Then or Next statement in For next loop as we have seen in my previous posts.

Syntax:

Do While (Criteria)
counter = counter + 1
'counter is has to be part of criteria
Loop

Do     counter = counter + 1
'counter is has to be part of criteria
Loop While/Until (Criteria)

Now, lets look at few examples on Do loops. I am sure these examples will help you in learning if you practice them.  Incase if you face any issue with replicating this code, please download the example file which has all example to try hands on. Also, you can make changes in code to test and enhance your skills.

Example 1:  Sheet named 'Dowhile_DoUntil1' has data of all the cities with their scores. We want to scroll till non-empty row and want to display number of non-empty row.  Remember we are only testing column 1.

-------------------------------------------------------------------------------------------------------------------------------

Sub Dowhile1()

Dim i As Long

'i is initialize to one as 1 is the minimum row on excel sheet and is very important step

i = 1

Do While Sheet1.Cells(i, 1) <> ""

i = i + 1
Loop
MsgBox "Last non-empty row is " & i - 1

End Sub

-------------------------------------------------------------------------------------------------------------------------------
Sub Dountil1()

Dim i As Long

i = 1

'i is initialize to one as 1 is the minimum row on excel sheet and is very 'important step
Do
i = i + 1
Loop Until Sheet1.Cells(i, 1) = ""

MsgBox "Last non-empty row is " & i - 1

End Sub

-------------------------------------------------------------------------------------------------------------------------------

If you observe carefully you will find the condition in Do while (While Sheet1.Cells(i, 1) <> "" )and Do Until (Until Sheet1.Cells(i, 1) = "")  is exactly opposite.

Example 2: We want to move and test across rows and columns., Like matrix. For all cells containing more than 150 should be colored green and below 50 should be marked red. In practical use I would even prefer to use conditional formatting if I have to only use two formats. But actually you can use for this for having n number of conditional formats.

-------------------------------------------------------------------------------------------------------------------------------

Sub Dowhile2()

Dim i As Long
Dim j As Integer
i = 1
j = 1

Do While Sheet2.Cells(i, j) <> ""

Do While Sheet2.Cells(i, j).Value <> ""
If Sheet2.Cells(i, j) < 50 And IsNumeric(Sheet2.Cells(i, j)) = True Then
Sheet2.Cells(i, j).Interior.Color = vbRed
ElseIf Sheet2.Cells(i, j).Value > 150 And IsNumeric(Sheet2.Cells(i, j)) = True Then
Sheet2.Cells(i, j).Interior.Color = vbGreen
ElseIf (Sheet2.Cells(i, j).Value >= 50 And Sheet2.Cells(i, j).Value <= 150) And IsNumeric(Sheet2.Cells(i, j)) = True Then
Sheet2.Cells(i, j).Interior.Color = vbYellow
End If
i = i + 1
Loop
j = j + 1
i = 1
Loop

End Sub

-------------------------------------------------------------------------------------------------------------------------------

Sub Dountil2()

Dim i As Long
Dim j As Integer
i = 1
j = 1

Do

Do
If Sheet2.Cells(i, j) < 50 And IsNumeric(Sheet2.Cells(i, j)) = True Then
Sheet2.Cells(i, j).Interior.Color = vbRed
ElseIf Sheet2.Cells(i, j).Value > 150 And IsNumeric(Sheet2.Cells(i, j)) = True Then
Sheet2.Cells(i, j).Interior.Color = vbGreen
ElseIf (Sheet2.Cells(i, j).Value >= 50 And Sheet2.Cells(i, j).Value <= 150) And IsNumeric(Sheet2.Cells(i, j)) = True Then
Sheet2.Cells(i, j).Interior.Color = vbYellow
End If
i = i + 1
Loop Until Sheet2.Cells(i, j).Value = ""
j = j + 1
i = 1
Loop Until Sheet2.Cells(i, j) = ""
End Sub

-------------------------------------------------------------------------------------------------------------------------------

IsNumeric(Sheet2.Cells(i, j)) = True test whether the value is numeric or not. IsNumeric() is very useful while scanning range of cells and you want to check or apply code only to cell with numeric values.

I will post some tips where you will see an extensive use of Do while/Until loop in MS Excel/VBA as Do while/until is most useful loop. Also, for your convenience I have posted link to download MS Excel file.

Download Do while/Until Loop

Kindly let us know your comments about this post.

We assure knowledge. Not SPAM.