Debug VBA macros - vba

I have a excel file with macros. It's used like template for our program. Program opens this file, call macros and put data there as parametrs. The question is how can I debug this macros when it's called from the app? For example, in Visual Studio I can use "Attach to process", maybe there is something like this in VBA?

I have a few different ways to perform debugging in Excel, and none of them are perfect or very sophisticated.
Use debug.print throughout your code to print to the Immediate window to see how the program is executing. This is useful in two scenarios - if you want to see generally how far along your program executed, or where it is in the process of executing, or alternatively, you can go in and add more detail using debug.print if your program is getting snagged somewhere specifically, and you want to see what is happening as the program is executing.
Create an array, enter log information into the array as the program executes, and print the array at the completion of the program execution. This is imperfect because it is not really useful in conditions where the program execution does not complete successfully, but it is useful in scenarios where you want to get some statistics about how the program ran as part of an autopsy.
Add Code Breaks in to the program so that you can see how the program is executing as it is run. Use the Immediate window to check on the values of variables in the program.
Again, none of these are perfect.

Related

Word VBA Document.ClosePrintPreview intermittently crashes with runtime error 4605

I am experiencing intermittent runtime error when doing the following in Word 2007 VBA:
Doc.PrintPreview
Doc.ClosePrintPreview
Here Doc is a valid document that was successfully opened by the same VBA script (not by the user).
Basically, I need print preview to open (for the purposes of forcing the update of all the fields) and then close it right away. The problem is that in about 20% of cases ClosePrintPreview crashes with runtime error 4605, complaining that the document is not in print preview mode, as if previous PrintPreview method call never did its job.
I can't visually confirm whether the PrintPreview actually did its job because the whole thing happens in pretty busy and tight loop, so Word does not update anything on the screen (even though I never turned off Application.ScreenUpdating).
It happens when the script is processing large documents that have several thousands of fields (print preview takes time to be generated when called interactively). It does not happen on simple, small-size documents.
And the whole thing happens intermittently, so I really can't figure out what triggers it. In about 80% of cases the script runs just fine.
So, the question is whether it is PrintPreview that really fails (which is not good and would need to be addressed, because I call it for a reason) or is it just ClosePrintPreview that gets confused and I could safeguard it with something like
If Application.PrintPreview = True Then Doc.ClosePrintPreview
Has anyone seen anything similar?

ABAP debugger: How do i get to the start of execution of my program without using a breakpoint

Whenever I run my program on a ABAP debugger -without setting a breakpoint- it starts executing the program from the SAP ABAP programs running under my program and I have to keep pressing F5/F6 to get to start of my code. This wastes my time.
How do I let ABAP debugger know I want to start right from the start of my own code, and I do not want to debug SAP code.
There are two options:
You might want to raise a SAPnet issue since this might be considered a bug in the processing of the statement BREAK-POINT ... AT NEXT APPLICATION STATEMENT
You might want to take a look at Layer Aware Debugging, which does come in handy for other situations as well.
If you use SE38 to start your ABAP-Program there you find a DEBUGGING-Button.

Use Excel solver with calculations by an external program

Currently, I have a spreadsheet which uses an external program to do calculations (let's say it's an aerodynamic calculation tool). In Excel VBA, I update the inputs to the program via a UDF at the spreadsheet level ( =input("var1",1.234)).
Then, using VBA, I write the input file, run the external .exe, and read the output file. Outputs are again reported to the spreadsheet level via a UDF (=output("var2"))
I would like to use the Excel Solver function to make an optimization of the spreadsheet. Here, I would like it to change the input values ( via the =input() function) to get the optimum in the outputs (via the =output() function). The solver should be able to change the inputs, wait for the new calculation to be made (via the external .exe) and then resume when it gets the outputs.
So far I've found no reliable way to make it work. The Excel solver does not know that it needs to wait for the .exe to finish, even when I embed the shell(.exe) command in the input UDF....the solver still plows through as if nothing was happening.
Expectedly, it comes up with bunk since the output is out of sync with the input. I've pried open the SOLVER.XLAM (...ahemm..) to find a way to insert a wait statement, but that wasn't much help; the interface ends where the VBA interfaces with the SOLVER.dll, which places hooks into Excel to run the Excel calculation directly from the .dll ...so no help to me.
So far I'm stumped. Nobody seems to have encountered this before. I've tried looking into OpenSolver.org version, but they also end at some mysterious .dll or .exe interface. Any ideas?
(BTW: I have no access to the external program code, if you're wondering.... an .exe and some text files is all I get).
OpenSolver should work if you use the NOMAD solver, which does all calculations directly inside the spreadsheet. See http://opensolver.org/non-linear-nomad-integration/ for more information.

Scripting Language with "edit and continue" or "hot swap" support? ( Maybe possible in Lua?)

I am making my existing .Net Application Scriptable for non programming users. I added lua, it works like a charm. Then I added debug functionality(pause/continue/step) via debug.sethook. It works also like a charm.
Now I realize that my Application needs edit and continue feature like Visual Studio has it. You pause the execution can edit the code and then continue from your current state with changes applied. This feature is very important to me. I thought this would be easy to do for scripting languages.
Everywhere I read that scripting languages can do this. But even after spending hours of searching I haven't found an Lua implementation yet. It hasn't to be Lua but hot swapping code in Lua would be my first choice.
How can the ability for the user be offered to pause and edit the script and than continue the execution with changes applied?
NOTE: It doesn't have to be Lua every scripting language would be okay
Update
#Schollii
Here is an example:
function doOnX()
if getValue() == "200" then
value = getCalculation()
doSomething() -- many function calls, each can take about 2s
doSomething()
doSomething()
print(value)
doX(value)
end
end
doOnX()
Thank you for your suggestions. This is how it might work:
I will use https://github.com/frabert/NetLua Its a very cool, well written 100% C# Lua Interpreter. It is generating an AST tree first and then directly executing it.
The parser needs to be modified. In Parser.cs public Ast.Block ParseString(string Chunk) there is a parseTree generated first. parseTree.tokens[i].locations are containing the exact position of each token. The Irony.Parsing.ParseTree is then parsed again and is converted to a NetLua.Ast.Block but the location information is missed. I will need to change that so later I will know which Statement is in which line.
Now each Statement from the AST tree is directly executed via EvalBlock. Debug functionality (like I have in my C Binding lua Interpreter DynamicLua via debug.setHook) needs to be added. This can be done in LuaInterpreter.cs internal static LuaArguments EvalBlock(`. Pause/continue/step functions should be no problem. I also can now add current line Highlighting because each statement contains position line information.
When the execution is paused and the code was edited the current LuaContxct is saved. It contains all variables. Also the last Statement with the last execution line is saved.
Now the code String is parsed again to a new AST tree. It gets executed. But all statements are skipped until the saved statement with the line statement is reached. The saved LuaContext is restored and execution can continue with all changes applied.
New variables could be also added after the last executed line, because a new NetLua.Ast.Assignment Statement could just add a new variable to the current LuaContext and everything should just work fine.
Will this work?
I think this is quite challenging and triicky to do right.
Probably the only way you could do that is if you recompile the chunk of code completely. In a function this would mean the whole function regardless of where edit is in function. Then call the function again. Clearly the function must be re-entrant else its side effects (like having incremented a global or upvalue) would have to be undone which isn't possible. If it is not reentrant it will still work just not give expected results (for example if the function increments a global variable by 1 calling it again will result in the global variable having been increased by 2 once the function finally returns).
But finding the lines in the script where the chunknstarts and ends would be tricky if truly generic solution. For specific solution you would have to post specific examples of scripts you want to run and examples of lines you would want to edit. If the whole user script gets recompiled and rerun then this is not a problem, but the side effects is still an issue, examples could help there too.

Ipython QtConsole %edit

When using the magic function %edit from QtConsole with IPython, the call does not block, and does not execute the saved code. It does however save a temporary file...
I think this is intended behavior due to GUI editors and uncertainty, and whatever that reason is for not being able to communicate with subprocess (pyZMQ?).
What do you suggest as the best way to mix %edit/%run magics?
I would not mind calling two different commands (one to edit, and one after I have saved and execution is safe). But those commands need a way to synchronize this target file location, or someone to persist storage, and probably need some crude form of predicatably generating filenames such that you can edit more than one file at a time, and execute in arbitrarily. Session persistence is not a must.
Would writing my own magic do any good? Hope we can %edit macros soon, that would do well enough to make it work.
you shoudl be able to do %edit filename.py and %run filename.py. The non blocking behavior is expected, and IIRC due to technical reason. Not unsurmountable but difficult.
You could define your own magic if you wish, improvement are welcomed.
Hope we can %edit macros soon, that would do well enough to make it work.
For that too, PR are welcomed. I guess as a workaround/option you can %load macro which would put macro on input n+1 , edit it and redefine it, that might be a good extension for a cell magic %%macro macroname
If you have some executable code on your input (from QtConsole), you can type
%edit 1-5
This fires the editor, creates a temporarily file (automatically managed), and loads your input lines. This is nearly enough, now how to retrieve the name of that temp file pragmatically?
I see the print statement on Stdout, but its not visible to QtConsole AFAIK. Could maybe redirect stdout to catch that line, but that may not be an option anyway if your doing something else with stdout.
If I could retrieve the full pathname that was just created, this would be cake. Store it where some magics will know how to find it. Then issue a followup command when ready,pops the name off the stack, loads it into a macro, and run. All this with 2 input commands and no names to remember (unless you want to find and use that macro again, but for 1 shot stuff...)
How do I catch or retrieve the path of that temporary file?