📅  最后修改于: 2023-12-03 15:05:48.607000             🧑  作者: Mango
In VBA, loops are used to execute a set of statements repeatedly until a certain condition is met. The While
loop is one of the most commonly used loops in VBA. The While
loop will execute the statements inside the loop while the condition is true.
The basic syntax for the While
loop is as follows:
While condition
'statements
Wend
The condition
is a logical expression that returns either True
or False
. If the condition is True, then the statements inside the loop will be executed.
Let's create a simple VBA code that uses a While
loop to iterate through an array of integers and prints out the values that are less than 5:
Sub WhileLoopExample()
Dim i As Integer
Dim arr() As Integer
arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
i = 0
While arr(i) < 5
Debug.Print arr(i)
i = i + 1
Wend
End Sub
In this example, we declare a variable i
and an array arr
of integers. We assign values to the array and then use a While
loop to iterate through the array until the value of arr(i)
is greater than or equal to 5.
In conclusion, the While
loop is a widely used loop in VBA that allows for repetitive execution of statements based on a specified condition. It is important to ensure that the condition is carefully defined to avoid infinite loop situations in the code.