Monday, August 29, 2005

Loop in VBA Easy Example

There are different versions of looping in VBA. Here is an example of the Do While version.

Sub letsLoop()
Dim intCounter As Integer

intCounter = 1 'Set the counter to 1

Do While intCounter <3'Loop while value of intCounter less then 3
MsgBox intCounter 'show message box with value of intCounter
intCounter = intCounter + 1 ' increase value of intCounter by 1
Loop 'loop again

End Sub

1 comment:

Anonymous said...

Thanks Orlando :)

I had not used loops before but this example taught me quick enough that I could adapt it to what I needed.

Here is a sample of what I ended up doing with your example Orlando. This script records the value of a control as a variable and uses that number to count down from.

Ultimately this script appends data from one table into another over and over again until the counter reaches 0.

Select Case MsgBox("You are about to add " & [UnitsRec] & " unit(s) to inventory." & _
vbCrLf & " Click ""Yes"" to ADD TO INVENTORY, ""No"" to cancel.", vbYesNo + vbExclamation, "Enter into Inventory?")

Case vbYes

' ADDS A NEW RECORD TO "VEH3b" FOR EVERY UNIT RECEIVED ON CURRENT ORDER BEING VIEWED
Dim NumOfNewRecords As Integer
NumOfNewRecords = UnitsRec

Do While NumOfNewRecords > 0

' SHOUTS CURRENT NUMBER IN LOOP. TESTS TO SEE IF "NumOfNewRecords" IS COUNTING DOWN FROM "UnitsRec".
' MsgBox NumOfNewRecords

DoCmd.RunSQL ("INSERT INTO tbl_VEH3b ( POrderNum, PSlipInvID ) " & _
"SELECT tbl_VEH3c.POrderNum, tbl_VEH3c.PSlipInvID " & _
"FROM tbl_VEH3c " & _
"WHERE (((tbl_VEH3c.ID)=[Forms]![frm_VEH3c]![ID]));")


NumOfNewRecords = NumOfNewRecords - 1 ' DECREASE VALUE OF "NumOfNewRecords" BY 1

Loop