Using For Statements and Templates about it
If I do not use VBA for a while
I forget a basic thing such as a For statement well.
For such a time
I will make a template that I can copy and use.
The declaration of integer variables and For statements
are used in sets.
Let's make it a template at once.
I write codes in the For statement what I often use.
Please change according to the situation.
How to use For statement 1:
First of all, I will make the template of the simplest usage.
Start with "i = 1".
Run VBA in the For statement
"Next i" will increment i by 1 and "i = 2".
Since i is less than or equal to 5
Execute again VBA in the For statement.
"Next i" will increment i by 1 and "i = 3".
Repeat such a loop
When i is incremented by 1 and becomes "i = 6"
Since i is larger than 5, Excel ends the For statement.
Code here
Sub macro180325a() Dim i As Integer |
Result:
How to use For statement 2:
Next, to rewrite "How to use For statement 1",
Iwill make i be +2 on Next i.
After "For i = 1 to 5"
Add "Step 2",
Make it "For i = 1 to 5 Step 2".
Actually "Step 1" is omitted in "How to use For statement 1".
When Step is omitted, the increment of i becomes +1.
Any integer can be specified after Step.
Code here
Sub macro180325b() Dim i As Integer |
Result:
How to use For statement 3:
Again, to rewrite "How to use For statement 1",
I will write a code that can go out in the middle of a For statement depending on the condition .
By describing "Exit For" in the For statement
You can leave the For statement on the way.
"Exit For" can be used many times in the For statement.
For condition judgment, use the If statement.
Code here
Sub macro180325c()
Dim i As Integer |
Result when flag = 0:
If flag of above code is set to other than 0,
It is the same execution result as "How to use For statement 1".
How to use For statement 4:
Next, to rewrite "How to use For 3",
I will make it another code.
If you want to go to the next loop
without executing rested code in the For statement depending on the condition,
you can use this code.
Use "GoTo" to jump to the last line of the For statement.
"GoTo" jumps to the specified line label and continues execution.
You can specify the line label with "Any Name:".
Code here
Sub macro180325d() Dim i As Integer |
Result:
How to use For statement 5:
The next is how to use nested For statements.
Declare two variables i and j.
i and j are used in the For statements.
Code here
Sub macro180325e() Dim i As Integer, j As Integer |
Result:
| 固定リンク
この記事へのコメントは終了しました。

コメント