How can I step into a line that is normally not called? - vb.net

Sometimes, I want to manually put the execution point to a certain line.
Because I don't want it to normally happen, but only when I put the execution point to this line manually, I name it this way:
If 0 Then
_SomeValue = "This can pnly be hit by setting the execution here manually"
End If
In VB6, it worked. It was one of my favorite ways to do some things.
In VB.NET, I am unable to do put the executor to this line.
Each time I do, it is set to the next line.
Is there any way to do what I want?
I got the suggestion to try If False Then, but it doesn't work for me:

Related

VBA Macro running too fast

It's weird that I'm finding ways to slow down my macro. Apart from Doevents and other time delay techniques, which are basically a workaround, is there a way through which we can get around the asynchronous execution. As in, I want the VBA code to behave like this:
start executing line 1>finish executing line 1>move to line 2;
Forgive if I'm wrong but currently it seems to follow:
Start executing line 1>without caring whether line 1 finished or not start executing line2
If you are calling external programs (vbs, exe) then the vba isn't getting any feedback on the process at all. It calls the programs and moves on to the next line of code (the vba doesn't know if/when the external programs finishes).
One way to slow this process down would be to put a application.wait or application.sleep between the calls, but that is also a workaround. Please post your actual code and perhaps we can troubleshoot further.
if the code is about refreshing data, use Refresh method with backgroundquery=False in a For Loop instead of RefreshAll.
For Each con In Me.Connections
con.ODBCConnection.BackgroundQuery = False
con.Refresh
Next

Capture Variable/Object Name causing the error

How can I capture the variable name or object name causing an error in VBA?
Ex
Sub test()
On Error GoTo Handler
i = 0
n = 1/i
Handler:
Select Case variablename
Case "n"
'do something................
The error is not being caused by a variable. The error is caused by the line of code that attempts to divide 1 by 0. The assignment doesn't actually happen.
The best way I've found to diagnose issues when I'm actively developing is to have Stop and then Resume in the error handler.
Public Sub func()
On Error GoTo ErrHandler
'... some code here ...
Exit Sub
ErrHandler:
Stop
Resume
End Sub
The way this works is, when there is an error VBA will break (pause the execution, show the instruction pointer arrow and yellow highlighting) on the Stop. You can step to the Resume and then once more to find out which specific line of code is causing the error.
Once you start to understand what errors you are encountering you can build individual If ... Then cases for them to handle each appropriately. When you are ready to release your code into a production environment (i.e., for other users), you would need to replace the Stop/Resume with an unexpected error handler that either logs it or displays it to the user.
While Blackhawk's answer works fine for a small example, I personally prefer to avoid modifying code to track down errors like that. If I'm working on a lot of files trying to track down a nasty bug, it's entirely possible that I might forget to remove any "special code" like Stop statements, etc. after I've finished debugging. If any such code makes it to production, that can be quite embarrassing for me. In addition, it can be annoying having to add this code to many different places in order to figure out where the error is happening in the first place (it's not always as obvious as in your example!).
For these reasons, I prefer to use the facilities provided by the VBA Editor. So:
Open the VBA Editor.
Go to Tools > Options.
Select the General tab and click the Break on All Errors radio button.
Click OK.
Now run your code and you'll notice that when it reaches this line:
n = 1/i
you'll get an error dialog saying what the problem is ("Run-time error '11': Division by zero") and you'll get the option to click the "Debug" button on the dialog, which will break execution at the above line and will highlight it in yellow.
Once you're done with your debugging and find the error that had been troubling you, you can go back to the VBA Editor options and revert the "Error Trapping" setting back to the default option ("Break on Unhandled Errors").
This way, you've done no changes to the code that you need to remember to revert before releasing the code and the actual operation to set/unset this behaviour only takes a few clicks.

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.

Run Time Error 1004 When Inserting Rows/Columns

So I'm running into the lovely run time error 1004: Application defined or object defined error.
The bear of it is, half the time the code in VBA runs correctly with no problems, and the other half it falls on its face. The third line ("Mgmt.List.....") is run in a loop normally, but it has no problems messing up on me in this simple macro.
Sub whyyyy()
Dim Mgmt As Worksheet
Set Mgmt = Sheets("Mgmt MarginAnalysis")
Mgmt.ListObjects("Table4").ListRows.Add (3)
End Sub
The line
Mgmt.ListObjects("Table4").ListRows.Add (3)
is extra special, as when it's run in the loop, it will sometimes work the first time, but fail the second time. Or it will just fail outright.
Don't really know what makes it work and what doesn't. This just started happening, and the worksheet/table combination seems to only happen to tables I've just inserted recently (not by using VBA).
Are you sure, the Sheets("Mgmt Margin Analysis") has table named "Table4". If you are creating the table on runtime, chances are that, it will not be assigned the same name ("Table4") everytime it is created.
Please ensure you assign this name in your code, and do not let Excel to choose the name for you.

Strange / unstable behaviour on CreatePivotTable()

I am writing VBA code to automate some processes in Excel and I am encountering a very strange behavior for which I have not been able to find documentation / help.
I have a procedure MAJ_GF that first executes function GF.Update, checks the result, and then launches procedure GF.Build (which basically takes the data obtained by GF.Update from different worksheets and does a bunch of stuff with it).
At some point, this "bunch of stuff" requires using a pivot table, so GF.Build contains the following line:
Set pvt = ThisWorkbook.PivotCaches.Create(xlDatabase, _
"'source_GF'!R1C1:R" & j & "C" & k).CreatePivotTable("'TCD_GF'!R4C1", "GFTCD1")
The strange behavior is this:
when I run MAJ_GF, VBA properly executes GF.Update, then launches GF.Build, and stops at the line described above complaining "Bad argument or procedure call"
when I manually run GF.Update, then manually run GF.Build, everything goes smoothly and GF.Build does what it has to do from beginning to end with no errors
even stranger, when I set a break-point on the incriminated line, run MAJ_GF then VBA pauses on the line as expected, and when I say "Continue"... it just continues smoothly and with no errors !
I turned this around and around and around, double-checked the value of every variable, and this just makes no sense.
Ideas anybody?
Few ideas come to my mind:
There's still some update going on in the background. Try DoEvents and Application.Wait before the line you mentiond
Also check, if any data connections are able to update in the background - if so disable the background refresh
Very rarely (usually in older version and when involving Charts), unhiding the Excel window (in case you used Application.Visible = False and enabling ScreenUpdating helped..
Are you using any "exotic" references/add-ins? Disable them and see if the problem persists.
Try restarting your machine
Not that I'm too optimistic that either will solve your problem - but give it a try! Best of luck!