Sunday 2 October 2011

VBA Tip - Screen Updating

Say you've written some VBA code that does various things with a spreadsheet. It does exactly what you want so you're essentially happy! However it may seem a bit slow or it just jumps around a lot on screen while it's running. In short it does the job but it doesn't look very professional.

Let's face it - you really don't want to change your code. It works! You just wish you could hide what was going on so that the user doesn't get distracted (or worse confused) by things jumping around on screen. If the user could switch the screen off while the code ran then that would be great! That's not going to happen but you can do the next best thing. Insert this line at the top of your lovely bit of code:

Application.ScreenUpdating = False

When Excel does something with a spreadsheet it redraws what's shown on screen. This simple line of code prevents that happening. The rest of your code is still doing all the same things as before but Excel doesn't draw any of it. This gives a really nice clean feel to a lot of processes.

At the end of your lovely code just remember to switch it back on again! Excel should do this for you but it's a good habit to get into just in case something doesn't quite go according to plan. (You can really confuse users if you forget!) The command is:

Application.ScreenUpdating = True

There is one added bonus, which you may have already guessed. Because Excel has got less work to do (no redrawing what's on screen) you may actually find that the same bit of code runs faster. Which is always nice!

No comments:

Post a Comment