VBA - Leave Do Until when specific row is reached - vba

In my VBA Code i go from the last row in my table to the top of my table. But i want that the Do Until Loop ends when it reached Row 10.
Right now I am using this Do Until Loop:
Do
' Do Something
Loop Until ActiveCell.Address = "$N$10:$BI$10"
How do i have to change my code that it will stop when it reached row 10?

Assuming rest of code is correct use:
Loop Until ActiveCell.Row = 10
If that fails you problem is logic in other parts of your code ie. ActiveCell never reaches row 10.

To answer your question in more theoretical fashion. There are multiple ways of exiting Do loops in VBA.
The proper way
1.1. While or Until at the begining
This checks the condition first, if the condition is met, it enters the loop and repeat with the condition being met at the start of every loop.
Do While i <= 5
'#code here
Loop
These two are equivalent.
Do Until i > 5
'#code here
Loop
1.2. While or until at the end
This is almost the same as what is described above. The only difference being, with sole Do statement at the beginning, your code-block always gets executed at least once! This can be particularly useful, when you want to execute something at least once, but don't want it to repeat unless a condition is met.
Do
'#code here
Loop While i <= 5
or
Do
'#code here
Loop Until i > 5
The enforced way
You can exit out of any loop, including Do with the so called Exit statement. This escapes the currently ongoing Do loop upon reaching the statement no questions asked. While you usually should try to avoid using the Exit statement, as in majority of cases it is possible to avoid using it with a proper condition at the While or Until portion of your code, it can come in handy in some cases.
Additionally, keep in mind, inside nested Do loops, Exit always exits only the innermost loop. This means, this would exit only the loop inside and let the others run, acting as a weird form of Continue
Do While (handler = True)
Do
'# execute me
If weird_condition = True Then
Exit Do
' i return to the "handler" loop
End If
field = field + 1
Loop Until field = field_amount
Loop
The not so nice enforced way
Alternatively, you can stop the entire exution, with the Stop statement. I would strongly advise against doing this, but technically it is a possibility so I'm listing it here. Similarly like End it ends the execution, but unlike End (eg. End Sub), it does not close any files or clear any variables - so technically this means you could use it to exit a loop. I would however recommend simply using the Exit statement instead. Can't really think of a case when I would ever use this.

Related

Performing a Do Until with an If statement until a certain value is reached

I am dealing with a large data sheet. I need code to subtract from a specific cell until the value is greater then a certain number. if that number isn't achieved I want it to go to 0.
For example if A3-A2 > Q5 then E3= A3-A2 if < Q5 do A3-A1. If this doesn't work E2=0. I need this to be continuous down the whole A column. So far, my code is as follows:
Do Until Range("A3").Offset(1, 0) - Range("A2") > Range("Q5")
If Range("A3").Offset(1, 0) - Range("A2") > Range("Q5") Then
Range("E3").End(xlDown) = Range("A3").Offset(1, 0) - Range("A2")
Else: Range("E3").End(xlDown) = 0
End If
Loop
It doesn't seem to like the way I enter it. and I don't think the offset is right.
It's a bad practice to use While, Until, While...WEnd.
Use unconditional Do...Loop with full-featured condition check code and Exit Do, which you can locate in any place of cycle, but not in beginning or end of it only.
-1? OK :)
MS F1: Tip The Do...Loop statement provides a more structured and flexible way to perform looping.
This "services" are for the lazy only. My denie of While and Until is the direct consequence of this statement exactly to achieve "structured and flexible", about which topick starter is asked for.

What's the difference between GoTo, using a Select, and using separate function?

To start off, I know that using Goto is never a good idea. But I'm having a hard time seeing the difference between the following structures...All of them process conditions sequentially, stop processing when they find a true value, then return control to a specified location in the code (the next line, as that's where this particular 'GoTo' target is). What is the difference between:
Ifs with GoTo:
If ConditionA then 'This is designed to skip the evaluation of condition B if condition A is met.
Do something
Goto Resume
End If
If ConditionB then
Do something
Goto Resume
End If
Resume:
Select Case:
Select ConditionIsTrue 'This will also skip the evaluation of B if A is true.
Case A
Do something
Case B
Do something
End select
Separate sub:
EvaluateConditions(condition)
Sub EvaluateConditions(condition)
If A then
DoSomething
Exit Sub
End If
If B then
DoSomething
Exit Sub
End If
End Sub
In general,
'goto' transfers the control of execution to the label that you are assigning. The control never comes back to where you use 'goto'. As the program flow is altered altogether, it is not advisable to use 'goto'. It becomes hard to debug.
When you write a subroutine and call it from other part of your code, the control is transferred back to the called part of your code once the execution of subroutine is complete. Hence, unlike goto, the program flow will not be affected and is always advisable to use subroutines instead of goto.
In case of select statement, it is not much different from multiple 'if-else' statements. Instead of having too many 'if-else' you can use 'select' to have a more cleaner code.
Being specific to what you have asked, all three does the same and there is no difference as such. What you choose depends on your requirement, number of conditions, re-usability of the piece of code and future enhancements.
If you have a very few conditions ( 2 or 3) and if you are sure that the piece of code doesn't require future enhancements, it is 'ok' to use goto.(still not a great choice)
If the piece of code should be reusable or even otherwise, using subroutine is the best choice. In fact, even if you have a very few conditions, it is better to use 'select' statement within the subroutine so that your code looks clean and is easy to add further conditions in future.

Running a loop while debugging VBA

The Problem
I am trying to debug some code, and somewhere in the middle I stopped at a breakpoint. Now I want to change some variables and run a certain loop several times.
How far did I get?
I know how to change the variables, but somehow I get stuck when trying to run the loop in the immediate window. Here is an example:
Dim i As Integer
Dim j As Integer
For i = 0 To 6
j=i ' Do something
Next i
I tried several variations of the code, but each time I get the following error:
Compile error: Next without for
Other relevant information
I tried searching but mostly found information about problems with loops, whilst I am quite sure the loop itself is fine. (Especially as I reached it before arriving at the breakpoint).
The only place I saw someone addres this situation, he reduced the loop to a single line, however to do this every time would be very impractical in my case.
I realize that I could call a function containing the loop, and then the function call would probably work, but again this feels quite impractical. So I guess it boils down to the following question.
The question
What is a practical way to run a loop whilst debugging VBA code in Excel?
There is actually a way for using loops or other multi-line statements in the Immediate Window - using a colon : to separate statements instead of a new line.
Full solution is described here.
Note that in the Immediate Window you also don't have to declare the variables using a Dim statement.
To summarize, your snippet would look something like this:
For i = 0 To 6: j=i: debug.Print i+j: Next i
I think I understand your question. You want to run a multi-line code block (i.e. the loop) in the Immediate Window. This throws errors because the Immediate Window is only intended for single lines of code.
I don't have any suggestions other than those you already mentioned. I'd recommend putting your test loop into a separate function and calling that from the Immediate Window:
Sub Test()
Dim i As Integer
Dim j As Integer
For i = 0 To 6
j=i ' Do something
Next i
End
Another option is to set several breakpoints. You can also run one line of code at a time with F8.
What is likely the preferred method (i.e., what most people actually do) is use the full power of the IDE, which includes the Immediate, Locals and Watch panes. You can change the value of most variables at runtime by direct assignment in the Immediate Pane (i=6 will do exactly what you think it should do). The IDE also allows you to set breakpoints, add watch conditions, step through code line-by-line using the F8, step through function or procedure calls using Shift+F8, stepping over (and back) through code using the mouse/cursor, and with a few exceptions, you can even add new variables during runtime.

VBA: Why do people include the variable's name in a "Next" statement?

I have always written my For-loops like this:
For foo = 1 to 10
' do something
Next
However, when I read code snippets online, people always do this:
For foo = 1 to 10
' do something
Next foo
I have not noticed any difference between the two, and I can't find any documentation on next statement is more desirable. What is the difference between those two (if any)?
The counter after the Next statement is optional. It used to be required in BASIC-derived languages, but this is no longer the case in VBA.
You can check the VBA reference:
If you omit counter in a Next statement, execution continues as if counter is included. If a Next statement is encountered before its corresponding For statement, an error occurs.
The reason people still add the counter it to increase readability.
It's for when you have multiple for loops.
For example,
For i to j
For k to l
next k
next i
Otherwise, the next is ambiguous. It's not absolutely necessary, as the loop will still work without it, but it's just good practice to have it marked for the sake of anyone else reading your code.

While loop - time of exit

This question applies I suppose to programming in general, but my application is built in MATLAB (based on C++):
In a while loop, if the while condition is no longer satisfied, does the loop run to its completion or does it exit at the exact moment that the conditions of the while loop are no longer satisfied?
e.g.
x = 1
while (x = 1)
{
x = 0
(some code)
}
In this case, does (some code) run?
PS. I know the syntax is terrible, it's just to illustrate the situation
It runs to completion. The while is only considered at entry to the loop block. So yes, (some code) does run.
it will only check at the entry of loop block. If it satisfies the condition, then it will run to completion, of course you can always choose to break the loop, if not then it will not enter the loop at all.