I would like to test if a procedure is called directly by the user (so it is on top of the call stack, see ctrl+L in debug mode) or called from another procedure.
Does someone know a way to do this without tracking the call stack in a parameter passed in each procedure?
I tried to do this using a public parameter topOfCallStackFound and then adding to each procedure some code like:
select case topOfCallStackFound
case false
currentProcedureIsTopOfCallStack = true
topOfCallStackFound = true
case true
currentProcedureIsTopOfCallStack = false
end select
But this doesn't work because VBA remembers the value of topOfCallStackFound after code execution is finished! The lifetime of topOfCallStackFound only ends when the workbook is closed, an end command is given or in a few other not useful circumstances. If it is possible to end the lifetime of topOfCallStackFound when code execution is finished and/or reinitializing topOfCallStackFound to false when the user starts new code execution, I would be done.
Thanks!
in VBA there is no normal way to see the callstack.
This is because the accessing this callstack via api is part of the low level compiler that is not part of the VBA.
You can view the callstack view the windows, as the VBE compiles the VBA and runs it and therefore has access to the VBA callstack but it does not expose it to the VBA.
You can however use try to use something like this:
http://www.everythingaccess.com/vbwatchdog.htm
Related
I have a MS Access database that displays an error message about a SQL syntax error on launch. "Syntax Error in query. Incomplete query clause." It also shows another error a few seconds after I hit "OK" on the first one.
Here's the two errors: https://imgur.com/a/PesjIFk
But it doesn't tell me where the syntax error is. There are SQL statements in a bunch of different places all over this project. This is a really large project and it wouldn't be practical to just look through all the code hoping that I notice an error someplace. How can I find out where this error is?
EDIT: Ok, so apparently you have to have a keyboard that has a "Break" key on it in order to even find where the error is. Wow. Fortunately I happen to have one. Here's the code that Access takes me to if I press break when I see the error message. This code is for a subform of another form. It highlights the first line (Private Sub Form_Current()).
Private Sub Form_Current()
If NumEnums > 0 Then
CurrentEnum = val(Nz(bit_value_edit.value)) 'Update CurrentEnum to the currently selected enum
Call UpdateEnumsLabel(Me.Parent![enums label]) 'Update label
End If
End Sub
...and here's UpdateEnumsLabel():
Public Sub UpdateEnumsLabel(ByRef label As Control)
If NumEnums > 0 Then
label.Caption = "Enums: " & CurrentEnum & "/" & NumEnums
Else
label.Caption = "Enums: 0"
End If
End Sub
The definition for CurrentEnum:
Public CurrentEnum, CurrentPort, CurrentFile, CurrentGroup As Long
I'm thinking that this error is unrelated to the code in Form_Current(), but Access is highlighting that line because the error happens when the form is opened. But the form doesn't contain anything that uses a query, so I'm confused as to what query Access has a problem with.
When the error Message pops up, Use Control+Break. It will take you to the line causes the issue.
You should also open a module and form the debug option in the VBA editor select "Compile All Modules"
And since it appears to happening on open/load, you can check both the macros and the main modules to find anything that triggers on AutoExec.
Often ctrl-break will hit the line where you errored out. However, in the case of multiple “events”, and code without error handling, then often the error occurs in the routine that called the code, not the actual code that caused the error.
What I would do launch the application (hold down the shift key to prevent any start up code, or forms running).
Now that you launched the application, but without forms or code running, then check for an autoexecc macro (if there is one, check what code it attempts to run).
If there not an autoexec macro in use, then check under file->options->current database. In this view, you can look/see/determine what the name of the start-up form is.
Once you determined the start-up form (or start up module/code) called from autoexec macro, then you can simply add a blank code module, and place in your code the SAME command that is used to start your application.
So let’s assume no autoexec macro, and you determine that the start-up form is frmMain.
So now, we can launch the application (hold down shift key to prevent any start up code from running). Now, type into a new “test” standard code module the following code:
Sub MyGo
Stop
Docmd.OpenForm "frmMain"
End sub
So you type in above code, hit ctrl-s to save the above code. Now with your cursor anyplace inside of the above code, you simply hit F5 to run.
At this point you hit/stop on the “stop” command in the debugger. At this point, you then can hit f8 to step to the next line of code. If the form in question calls other code etc., you still be able to single step, and “eventually” you hit the line which causes the error.
While the application may be large, a simple look at the start up forms (and huts then the start-up code) means that you ONLY really need to trace and look at the start up code – not the whole application.
This is probably the dumbest question I've ever asked here, but it's hard to find answers to things like this.
I have a program with a bunch of modules/subs that each calculate a different variable. They're pretty complex, so I like to keep them separate. Now I want an earlier module to skip to another module based on user input. I thought I could use the call (sub name) method for this, but then the program returns to where the call line was and continues on that module from where it left off.
Example:
Module 1:
Sub NewPracticeSub()
Call otherpracticesub
MsgBox ("We've gone back to this sub... :(")
End Sub
Module 2:
Sub otherpracticesub()
MsgBox ("We're in the other practice sub!")
End Sub
I don't want it to return to Module 1. What can I do to have it switch control to Module 2 without it then returning to complete Module 1 upon completion of Module 2?
I feel like I just used the most confusing language possible to explain all of this, but thank you for your help anyways!!
Edit: I know I used the words module and sub interchangeably, and I know they're different. I like to keep each sub (which are each very large in my program) in their own modules because it's easier to keep track of them, and easier to explain/demonstrate the application flow to other people.
I think all you're looking for is the command Exit Sub which will make the program leave the subroutine without continuing any further, But the way you usually want to do this is, rather than calling a Sub, rather call a Function that returns a boolean value.
So, for example:
Public Function MyFunc() as Boolean
....
If [good] MyFunc = True
Else MyFunc = False
End Function
Then you could do something along the lines of:
Sub MyCallingSub()
...
If MyFunc = True then Exit Sub
Else ...
End Sub
It just adds in A LOT more felxibility and ability to choose whether you want to continue further in your sub or not.
Hope that makes sense.
Other than using the ugly End statement which I will describe below (and strongly recommend you to avoid), I'm not aware of any way to circumvent the call stack. Even John's response necessarily returns to the calling procedure, and evaluates another statement to determine whether to proceed or end.
This may yield undesirable outcomes, which is why I hesitate to recommend it, in favor of properly structuring your code, loops, etc., with respect to the call stack.
In any case, here is how you can use the End statement within your child subroutines, without needing any sort of public/global variables. This still allows you the flexibility to decide when & where to invoke the End statement, so it need not always be invoked.
Sub NewPracticeSub()
Call otherpracticesub, True
MsgBox ("We've gone back to this sub... :(")
End Sub
Sub otherpracticesub(Optional endAll as Boolean=False)
MsgBox ("We're in the other practice sub!")
If endAll then End '## Only invoke End when True is passed to this subroutine
End Sub
Why I say this method should be avoided, via MSDN:
"Note The End statement stops code execution abruptly, without
invoking the Unload, QueryUnload, or Terminate event, or any other
Visual Basic code. Code you have placed in the Unload, QueryUnload,
and Terminate events of forms and class modules is not executed.
Objects created from class modules are destroyed, files opened using
the Open statement are closed, and memory used by your program is
freed. Object references held by other programs are invalidated.
The End statement provides a way to force your program to halt. For
normal termination of a Visual Basic program, you should unload all
forms. Your program closes as soon as there are no other programs
holding references to objects created from your public class modules
and no code executing."
It will always return but that doesn't mean its a problem. I suggest you use Exit Sub as follows:
Sub NewPracticeSub()
Call otherpracticesub
**Exit Sub**
'Nothing more can execute here so its no longer a worry
End Sub
Module 2:
Sub otherpracticesub()
MsgBox ("We're in the other practice sub!")
End Sub
I am just reworking my VB6 in .NET.
I have a function that is called NonNullString(byval uAny As Object) As String
In VB6 I worked with a sqlite wrapper, and a recordset's member could be accessed by using
Dim sString$
sString = r("somefield")
(without ".Value")
I have really many of these fields, and I changed most of them to ".Value", but for some I forgot it.
An exception is therefore raised in the function NoNullString, and I am looking for a way to quickly jump out of the function in order to see what the caller was and improve the code.
F5 does not do the job.
Does anybody have any ideas?
Thank you!
Press CTRL+L to see call stack. From there you can navigate through the stack.
You can then use Set Next Statement (CTRL+F9) on the End Function of your errored function. Two times F10 to complete execution of this function. Repeat this step till you are in the scope where you think the error originated. Then, if you are on x86 (so you have Edit&Continue available), fix your code, and drag your currently executed line to the moment when this fix would occur. And then try running your function again.
Unfortunately, you cannot Set Next Statement outside of the current block function/sub, which I was going to suggest originally.
In the following block of code, does VB.NET gracefully exit the With block if Var1 = 2?
With MyObject
.Property1 = "test"
If Var1 = 2 Then
Return True
End If
.Property2 = "Test2"
End With
Return False
I remember this being an issue in VB6 and causing headaches with unpredicable behaviour - is the same true of VB.NET?
According to MSDN, this still isn't possible:
If you need to exit before all the statements have been executed, put a label on the End With statement and use the GoTo Statement to branch to it. (...) You cannot transfer control either from outside a With block to inside it, or from inside it to the outside. You can call a procedure from inside the block, but control returns to the following statement.
Had to add another answer here, because I was mainly curious. Never used WITH much, and I can't recall ever exiting the block prematurely, but I just tested this under VB2010 and it appears to work just fine (ie as I would expect it to, in other words...
If Var1 =2, the function returns TRUE, and the value of MyObject.Property1 is "Test" but MyObject.Property2 has not be set.
It's possible that it worked this way in a test, but in a real app of significant size, with debugging turned off etc, etc, it could work differently, so, there's that to consider....
Is it better to show ProgressBar UserForms in VBA as modal or modeless? What are the best practices for developing progress indicators in VBA?
Modeless UserForms require the use of Application.Interactive = False, whereas Modal UserForms by their very nature block any interaction with the application until the core procedure has finished, or is cancelled.
If Application.Interactive = False is used, however, the Esc key interrupts code execution, so the use of Application.EnableCancelKey = xlErrorHandler and error handling (Err.Number = 18) is required in both the UserForm and the calling procedure.
Resource intensive calling procedures can also result in CommandButton_Click and UserForm_Activate events misfiring in modeless UserForms.
In general, progress indicators that use modal UserForms seem simpler, because the code that is being executed is fully contained in the UserForm module, and there is less need for passing of variables.
The problem, however, with using modal UserForms for progress indicators is that a separate UserForm module is required for every procedure that needs a progress indicator, because the calling procedure has to be inside the UserForm_Activate procedure.
So, while it is possible to have a single reusable progress indicator in a modeless UserForm, it will be less reliable than executing the code from within multiple modal UserForms.
Which way is better?
Thanks!
There's also a third way, using the Application.StatusBar.
You can even simulate a true progress bar by using a sequence of U+25A0 and U+25A1 characters.
I am going to close this one out and say Modal is the winner. I have tried both ways, but you end up trying to close too many loopholes with modeless userforms. Modal is more difficult because it is more strict, but it encourages you to break up your code into smaller chunks which is better in the long run anyway.
Definately Modal.
If you are going to consider Modeless, you ought to run it on a seperate out-of-process thread and not on the Excel.exe main thread.
I think that the initial topic is worth of replying since the question was formulated so nicely that google finds it first.
Section 1 - Theory
The first thing to say is that to transfer the variables between the modules is not difficult at all.
The only thing you need to do is to create a separate module and put there all the global variables. Then you will be able to read them everywhere in all forms, sheets, modules.
The second thing is the window should be a MODELESS. Why that?
The answer is to keep the mobility of the code, i.e.
the function where the most routine process is executed is not to be located in the UserForm module
you can call the window with progress bar from everywhere and
the only connection between the routine function/procedure are the global variables
This is a great advantage to be versatile here.
Section 2 - Practice
1) Create a module "Declaration" with the global variables:
Public StopForce As Integer
'this variable will be used as an indicator that the user pressed the cancel button
Public PCTDone As Single
' this is the % of the work that was done already
Public CurrentFile As String
' any other parameter that we want to transfer to the form.
2) Create the form with the button. In OnClick event of the button there should be a code where we refer to the global variable StopForce in Declaration module
Private Sub CommandButton1_Click()
Declaration.StopForce = 1
End Sub
3) Add one procedure where you update the progress bar
Sub UpdateProgressBar(PCTDone_in As Single)
With UserForm1
' Update the Caption property of the Frame control.
.FrameProgress.Caption = Format(PCTDone_in, "0%")
' Widen the Label control.
.LabelProgress.Width = PCTDone_in * _
(.FrameProgress.Width)
' Display the current file from global variable
.Label1.Caption = Declaration.CurrentFile
End With
End Sub
4) in any other module we must have the functions or the procedure/sub where the routine is done:
For i=1 to All_Files
Declaration.CurrentFile = myFiles (i)
FormFnc.UpdateProgressBar (i / .Range("C11").Value)
DoEvents
If Declaration.StopForce = 1 Then
GoTo 3
End If
Next i
Actually you have following properties, resulting in pros/cons depending on your need:
Type | Impact on UI | Impact on caller execution
----------|--------------|-----------------------------
Modal | Blocked | Blocked until Form is closed
Modeless | Not blocked | Continues
If you want to block the UI AND let the caller continue, then you need to open the Form in modal mode with Application.OnTime.