| Start |
|---|
| ALWAYS Use "Option Explicit" In the VBA Editor window, from the Tools menu select "Options": Then in the "Editor" tab, make sure that "Require Variable Declaration" is checked: Selecting this option will automatically put Small note: This is true for the modules, class modules, etc. that haven't been opened so far. So if you already had a look at e.g. the code of
Example : If you run the following code : You will get the following message : You have made an error by writing Now if you add the correct declaration : You will obtain an error message indicating precisely the error with **Note on Option Explicit and Arrays** (Declaring a Dynamic Array): You can use the ReDim statement to declare an array implicitly within a procedure.
|
| Work with Arrays, Not With Ranges Office Blog - Excel VBA Performance Coding Best Practices (opens new window) Often, best performance is achieved by avoiding the use of More tips and info with timed examples can be found in Charles Williams's Writing efficient VBA UDFs (Part 1) (opens new window) and other articles in the series (opens new window). |
| Switch off properties during macro execution It is best practice in any programming language to avoid premature optimization. However, if testing reveals that your code is running too slowly, you may gain some speed by switching off some of the application’s properties while it runs. Add this code to a standard module: More info on Office Blog - Excel VBA Performance Coding Best Practices (opens new window) And just call it at beginning and end of macros: While these can largely be considered "enhancements" for regular One caveat: While disabling these settings will improve run time, they may make debugging your application much more difficult. If your code is not functioning correctly, comment out the This is particularly important if you are writing to cells in a worksheet and then reading back in calculated results from worksheet functions since the NOTE: Since these are properties of the With error handling: |
Use VB constants when available can be used in place of in order to improve readability. Use Object Browser to find available VB constants. View → Object Browser or F2 from VB Editor. Enter class to search View members available |
| Avoid using SELECT or ACTIVATE It is very rare that you'll ever want to use If you're just starting to learn VBA, you'll often be suggested to record your actions using the macro recorder, then go look at the code. For example, I recorded actions taken to enter a value in cell D3 on Sheet2, and the macro code looks like this: Remember though, the macro recorder creates a line of code for EACH of your (user) actions. This includes clicking on the worksheet tab to select Sheet2 ( There are multiple issues with using
When you're coding in VBA, all of the "typing" actions (i.e. (The BETTER example above shows using intermediate variables to separate different parts of the cell reference. The GOOD example will always work just fine, but can be very cumbersome in much longer code modules and more difficult to debug if one of the references is mistyped.) **NOTE: the macro recorder makes many assumptions about the type of data you're entering, in this case entering a string value as a formula to create the value. Your code doesn't have to do this and can simply assign a numerical value directly to the cell as shown above. **NOTE2: the recommended practice is to set your local workbook variable to |
| Always define and set references to all Workbooks and Sheets When working with multiple open Workbooks, each of which may have multiple Sheets, it’s safest to define and set reference to all Workbooks and Sheets. Don't rely on The following code example demonstrates how to copy a range from “Raw_Data” sheet in the “Data.xlsx” workbook to “Refined_Data” sheet in the “Results.xlsx” workbook. The procedure also demonstrates how to copy and paste without using the |
| Use descriptive variable naming Descriptive names and structure in your code help make comments unnecessary is better than This is especially helpful when you are copying data from one place to another, whether it's a cell, range, worksheet, or workbook. Help yourself by using names such as these: If you declare multiple variables in one line make sure to specify a type for every variable like: The following will only declare the last variable and the first ones will remain |
| Document Your Work It's good practice to document your work for later use, especially if you are coding for a dynamic workload. Good comments should explain why the code is doing something, not what the code is doing. If your code is so obscure that it requires comments to explain what it is doing, consider rewriting it to be more clear instead of explaining it through comments. For example, instead of: Clarify the code to be easier to follow, such as: |
| Error Handling Good error handling prevents end users from seeing VBA runtime errors and helps the developer easily diagnose and correct errors. There are three main methods of Error Handling in VBA, two of which should be avoided for distributed programs unless specifically required in the code. or Prefer using: On Error GoTo 0If no error handling is set in your code, On Error Resume Next
Had we not used the Note: It is also a best practice to immediately reset the error handler as soon as you no longer need the On Error GoTo This method of error handling is recommended for all code that is distributed to other users. This allows the programmer to control exactly how VBA handles an error by sending the code to the specified line. The tag can be filled with any string (including numeric strings), and will send the code to the corresponding string that is followed by a colon. Multiple error handling blocks can be used by making different calls of Note: It is essential that the If you exit your method with your error handling code, ensure that you clean up:
|
| Never Assume The Worksheet Even when all your work is directed at a single worksheet, it's still a very good practice to explicitly specify the worksheet in your code. This habit makes it much easier to expand your code later, or to lift parts (or all) of a As an example, the following code is ambiguous -- but works! -- as long the developer doesn't activate or change to a different worksheet: If The best practice is to always identify which worksheet to which your code refers: The code above is clear in identifying both the workbook and the worksheet. While it may seem like overkill, creating a good habit concerning target references will save you from future problems. |
| Avoid using ActiveCell or ActiveSheet in Excel Using
|
| WorksheetFunction object executes faster than a UDF equivalent VBA is compiled in run-time, which has a huge negative impact on it's performance, everything built-in will be faster, try to use them. As an example I'm comparing SUM and COUNTIF functions, but you can use if for anything you can solve with WorkSheetFunctions. A first attempt for those would be to loop through the range and process it cell by cell (using a range): One improvement can be to store the range values in an array and process that: But instead of writing any loop you can use Or, for more complex calculations you can even use And finally, running above Subs 25,000 times each, here is the average (5 tests) time in milliseconds (of course it'll be different on each pc, but compared to each other they'll behave similarly):
|
| Avoid re-purposing the names of Properties or Methods as your variables It is generally not considered 'best practice' to re-purpose the reserved names of Properties or Methods as the name(s) of your own procedures and variables. Bad Form - While the following is (strictly speaking) legal, working code the re-purposing of the Find (opens new window) method as well as the Row (opens new window), Column (opens new window) and Address (opens new window) properties can cause problems/conflicts with name ambiguity and is just plain confusing in general. Good Form - With all of the reserved words renamed into close but unique approximations of the originals, any potential naming conflicts have been avoided. While there may come a time when you want to intentionally rewrite a standard method or property to your own specifications, those situations are few and far between. For the most part, stay away from reusing reserved names for your own constructs. RemarksWe all know them, but these practices are far less obvious to someone starting to program in VBA. |
Read Article
https://develop.horje.com/learn/1434/reference