Debugging is a very powerful way to have a closer look and fix incorrectly working (or non working) code.
First thing you need to do during debugging is to stop the code at specific locations and then run it line by line to see whether that happens what's expected.
Stopkeyword to a blank line to have the code stop at that location on runtime. This is useful if, for example, before declaration lines to which you can't add a breakpoint with F9
Debug.Printto print lines to the Immediate Window at runtime. You may also use
Debug.?as a shortcut for
Running code line by line is only the first step, we need to know more details and one tool for that is the watch window (View - Watch window), here you can see values of defined expressions. To add a variable to the watch window, either:
When you add a new expression you can choose whether you just want to see it's value, or also break code execution when it's true or when its value changes.
The immediate window allows you to execute arbitrary code or print items by preceeding them with either the
? ActiveSheet.Name- returns name of the active sheet
Print ActiveSheet.Name- returns the name of the active sheet
? foo- returns the value of
x = 10sets
* Getting/Setting values for variables via the Immediate Window can only be done during runtime
Whenever your code doesn't work as expected first thing you should do is to read it again carefully, looking for mistakes.
If that doesn't help, then start debugging it; for short procedures it can be efficient to just execute it line by line, for longer ones you probably need to set breakpoints or breaks on watched expressions, the goal here is to find the line not working as expected.
Once you have the line which gives the incorrect result, but the reason is not yet clear, try to simplify expressions, or replace variables with constants, that can help understanding whether variables' value are wrong.
If you still can't solve it, and ask for help: