5. Hide Page breaks
When we run a Microsoft VBA macro in a later version of Microsoft Excel, the macro may take longer to complete than it does in earlier versions of Excel. For example, a macro that required several seconds to complete in an earlier version of Excel may require several minutes to complete in a later version of Excel. This problem may occur if the following conditions are true:
* The VBA macro modifies the properties of many rows or columns.
* An operation has been performed that forced Excel to calculate page breaks. Excel calculates page breaks when we perform any of the following operations:
o We display a print preview of your worksheet.
o In Microsoft Office Excel 2003 and in earlier versions of Excel, we click Page Setup on the File menu.
o We modify any of the properties of the PageSetup object in a VBA macro.
* In Excel 2003 and in earlier versions of Excel, we selected the Page breaks check box on the View tab of the Options dialog box.
Solution: is to disable Page breaks using ActiveSheet.DisplayPageBreaks = False
6. Use 'WITH' statement
If we have to access an object's properties and methods in several lines, we
must avoid using object's name or fully qualified object path again and again. It is annoying for VBA processor as it needs
to fully qualify the object each time. (Isn't it annoying for us too when some work or something is told us again and again?
Got it Guys !
SLOW MACRO:-
Sheets(1).Range("A1:E1").Font.Italic = True
Sheets(1).Range("A1:E1").Font.Interior.Color = vbRed
Sheets(1).Range("A1:E1").MergeCells = True
FAST MACRO:-
With Sheets(1).Range("A1:E1")
.Font.Italic = True
.Font.Interior.Color = vbRed
.MergeCells = True
End With
The point here to understand is minimum qualifying of an object by VBA processor. i.e. using minimum dots/periods(.) in the code. This concept tells us to use [A1] rather than Range("A1") and Range("StockRange")(3,4) rather than Range("StockRange").Cells(3,4)
7. Use vbNullString instead of ""
Use vbNullString instead of ""(2 double quotes) : vbNullString is slightly faster than "", since vbNullString is not actually a string, but a constant set to 0 bytes, whereas "" is a string consuming at least 4-6 bytes for just existence.
For example: Instead of strVariable = "", use strVariable = vbNullString.
8. Release memory of Object variables
Whenever we create an object in VBA, we actually create two things -- an object, and a pointer (called an object reference). We might say, "VB does not use pointers", but it is not true. "VB does not let you manipulate pointers" is more precise. Behind the scenes, VB still makes extensive use of pointers. To destroy an object in VB, you set it to Nothing. But wait a minute. If all we ever use are object pointers, how can we set the object itself to Nothing? The answer is: We can't.
When we set a reference to Nothing, something called the garbage collector kicks in. This little piece of software tries to determine whether or not an object should be destroyed. There are many ways to implement a garbage collector, but Visual Basic uses what is called the reference count method.
When VB interprets the last line(where we generally sets our objects to Nothing), it will remove the existing reference. At this point, if the object has no more references, the garbage collector will destroy the object and deallocate all its resources. If any other references point to the same object, the object will not be destroyed.
Welcome to VBA Tips & Tricks. All VBA related information will be posted on this blog. Of late, VBA has been disregarded by many software professionals for .Net, c# and other technologies. This blog will also post articles related to them too Happy reading
Wednesday, February 8, 2012
To Optimize VBA Code for FASTER Macros_1
1. Analyze the Logic :-
Before optimizing the syntax, pay more attention in optimizing the logic. Without a good logic, a good written VBA macro program has no value. So streamline your program logic and get the best performance of macros.
2. Turn off ScreenUpdating
Avoid 'Screen Flickering' or 'Screen Repainting': Use
Application.ScreenUpdating = False 'To Turn Off at the start of code.
Application.ScreenUpdating = False 'To Turn on at the end of the code.
The ScreenUpdating property controls most display changes on the monitor while a procedure is running. When screen updating is turned off, toolbars remain visible and Word still allows the procedure to display or retrieve information using status bar prompts, input boxes, dialog boxes, and message boxes. You can increase the speed of some procedures by keeping screen updating turned off. You must set the ScreenUpdating property to True when the procedure finishes or when it stops after an error.
3. Turn off 'Automatic Calculations'
Whenever content(s) of a cell or range of cells are changed, the formulas dependent on them and Volatile functions are recalculated.
You may turn off the automatic calculation using
Application.Calculation = xlCalculationManual 'To turn off the automatic calculation
Application.Calculation = xlCalculationAutomatic 'To turn On the automatic calculation
Now, whenever due to the program logic(that due to macros dependent on existing formulas) you need to calculate the formulas, you may use the following code accordingly.
ActiveSheet.Calculate ' To calculate the formulas of Active Worksheet
Application.Calculate ' To calculate the formulas of Active workbook or all workbooks in current application.
4. Disable Events
Use Application.EnableEvents to tell VBA processor whether to fire events or not. We rarely fire an event for each cell we're changing via code. Hence, turning off events will speed up our VBA code performance.
Before optimizing the syntax, pay more attention in optimizing the logic. Without a good logic, a good written VBA macro program has no value. So streamline your program logic and get the best performance of macros.
2. Turn off ScreenUpdating
Avoid 'Screen Flickering' or 'Screen Repainting': Use
Application.ScreenUpdating = False 'To Turn Off at the start of code.
Application.ScreenUpdating = False 'To Turn on at the end of the code.
The ScreenUpdating property controls most display changes on the monitor while a procedure is running. When screen updating is turned off, toolbars remain visible and Word still allows the procedure to display or retrieve information using status bar prompts, input boxes, dialog boxes, and message boxes. You can increase the speed of some procedures by keeping screen updating turned off. You must set the ScreenUpdating property to True when the procedure finishes or when it stops after an error.
3. Turn off 'Automatic Calculations'
Whenever content(s) of a cell or range of cells are changed, the formulas dependent on them and Volatile functions are recalculated.
You may turn off the automatic calculation using
Application.Calculation = xlCalculationManual 'To turn off the automatic calculation
Application.Calculation = xlCalculationAutomatic 'To turn On the automatic calculation
Now, whenever due to the program logic(that due to macros dependent on existing formulas) you need to calculate the formulas, you may use the following code accordingly.
ActiveSheet.Calculate ' To calculate the formulas of Active Worksheet
Application.Calculate ' To calculate the formulas of Active workbook or all workbooks in current application.
4. Disable Events
Use Application.EnableEvents to tell VBA processor whether to fire events or not. We rarely fire an event for each cell we're changing via code. Hence, turning off events will speed up our VBA code performance.
Tuesday, January 3, 2012
VBA Controls:-
This section is about communicating with users using controls or a Userform. Learn how to use these controls in Excel 2010,
Excel 2007 or Excel 2003. You can directly place controls on a sheet or place them on a Userform.
1) Textbox: A textbox is an empty field where the user can fill in a piece of text. Learn how to draw a textbox on your worksheet, how to refer to a textbox in your Excel VBA code, and how to clear a textbox.
2) Listbox: A listbox, is a drop down list from where the user can make a choice. Learn how to draw a listbox on your worksheet and how to add items to a listbox.
3) Combobox: A combobox is the same as a listbox but now the user can also fill in his/her own choice if it is not included in the list. Learn how to draw a combobox on your worksheet and how to add items to a combobox.
4) Checkbox: A checkbox is a field which can be checked to store information. Learn how to draw a checkbox on your worksheet and how to refer to a checkbox in your Excel VBA code.
5) Option Buttons: Option buttons are the same as checkboxes except that option buttons are dependent on each other while checkboxes are not. This means that when you check one option button the other option button will automatically uncheck.
6) Userform: This chapter teaches you how to create an Excel VBA Userform (also known as a dialog box). You can download the Userform on this page as well.
Excel 2007 or Excel 2003. You can directly place controls on a sheet or place them on a Userform.
1) Textbox: A textbox is an empty field where the user can fill in a piece of text. Learn how to draw a textbox on your worksheet, how to refer to a textbox in your Excel VBA code, and how to clear a textbox.
2) Listbox: A listbox, is a drop down list from where the user can make a choice. Learn how to draw a listbox on your worksheet and how to add items to a listbox.
3) Combobox: A combobox is the same as a listbox but now the user can also fill in his/her own choice if it is not included in the list. Learn how to draw a combobox on your worksheet and how to add items to a combobox.
4) Checkbox: A checkbox is a field which can be checked to store information. Learn how to draw a checkbox on your worksheet and how to refer to a checkbox in your Excel VBA code.
5) Option Buttons: Option buttons are the same as checkboxes except that option buttons are dependent on each other while checkboxes are not. This means that when you check one option button the other option button will automatically uncheck.
6) Userform: This chapter teaches you how to create an Excel VBA Userform (also known as a dialog box). You can download the Userform on this page as well.
VBA Programming 2:-
7) Logical Operators: Do you want to execute code in Excel Visual Basic when more conditions are met? Or just one? Or none?
Logical operators are what you need! Logical operators such as And, Or and Not are often used in Excel VBA.
8) Range: The Range object which is the representation of a cell (or cells) on your worksheet is the most important object of Excel VBA. It has many properties and methods and they are essential to manipulate the content of your Excel worksheet. In this chapter you will discover the most useful properties and methods of the Excel VBA Range object. They enable you to obtain control over your Excel worksheet.
9) Events: This chapter teaches you how to program workbook and worksheet events. Events are actions performed by users which trigger Excel VBA to execute a macro. For example, when you open a workbook or when you change something on an Excel worksheet, Excel VBA can automatically execute a macro.
10) Array: An Excel VBA array is a group of variables. You can refer to a specific variable (element) of an array by using the array name and the index number.
11) Date and Time: Dates and Times in Excel VBA can be manipulated in many ways. Easy examples are given in this chapter.
12) Function and Sub: The difference between a function and a sub in Excel VBA is that a function can return a value and a sub cannot. In this chapter we will look at an easy example of a function and a sub. Functions and subs become very useful as program size increases.
Logical operators are what you need! Logical operators such as And, Or and Not are often used in Excel VBA.
8) Range: The Range object which is the representation of a cell (or cells) on your worksheet is the most important object of Excel VBA. It has many properties and methods and they are essential to manipulate the content of your Excel worksheet. In this chapter you will discover the most useful properties and methods of the Excel VBA Range object. They enable you to obtain control over your Excel worksheet.
9) Events: This chapter teaches you how to program workbook and worksheet events. Events are actions performed by users which trigger Excel VBA to execute a macro. For example, when you open a workbook or when you change something on an Excel worksheet, Excel VBA can automatically execute a macro.
10) Array: An Excel VBA array is a group of variables. You can refer to a specific variable (element) of an array by using the array name and the index number.
11) Date and Time: Dates and Times in Excel VBA can be manipulated in many ways. Easy examples are given in this chapter.
12) Function and Sub: The difference between a function and a sub in Excel VBA is that a function can return a value and a sub cannot. In this chapter we will look at an easy example of a function and a sub. Functions and subs become very useful as program size increases.
VBA Programming 1:-
This section is for users who want to get the most out of Excel VBA. Excel VBA Programming is not difficult, but you do need to know the keywords used in Excel VBA.
1) Variables: Excel VBA uses variables just like any other programming language. Learn how to declare and initialize an excel vba variable of type Integer, String, Double, Boolean and Date.
2) String Manipulation: There are many functions in Excel VBA we can use to manipulate strings. In this chapter you can find a review of the most important functions.
3) Calculate: Calculate with Excel VBA and add, subtract, multiply and divide values just like you are used to doing in Excel.
4) If Then Statement: In many situations you only want Excel VBA to execute certain code lines when a specific condition is met. The If Then statement allows you to do this. Instead of multiple If Then statements, you can use Select Case.
5) Cells: Instead of the more common Range object we could also use Cells. Using Cells is particularly useful when we want to loop through ranges.
6) Loop: Looping is one of the most powerful programming techniques. A loop (or For Next loop) in Excel VBA enables you to loop through a range of data with just a few lines of code.
1) Variables: Excel VBA uses variables just like any other programming language. Learn how to declare and initialize an excel vba variable of type Integer, String, Double, Boolean and Date.
2) String Manipulation: There are many functions in Excel VBA we can use to manipulate strings. In this chapter you can find a review of the most important functions.
3) Calculate: Calculate with Excel VBA and add, subtract, multiply and divide values just like you are used to doing in Excel.
4) If Then Statement: In many situations you only want Excel VBA to execute certain code lines when a specific condition is met. The If Then statement allows you to do this. Instead of multiple If Then statements, you can use Select Case.
5) Cells: Instead of the more common Range object we could also use Cells. Using Cells is particularly useful when we want to loop through ranges.
6) Loop: Looping is one of the most powerful programming techniques. A loop (or For Next loop) in Excel VBA enables you to loop through a range of data with just a few lines of code.
VBA Basics 2:-
6) Debug Macros: Before you execute your VBA-code you can first debug your macro. This way most of the errors can be corrected before you execute your code.
7) Objects, Properties and Methods: In this chapter you will learn more about Excel VBA objects. An object has properties and methods. Excel Visual Basic is a semi-object oriented programming language. Learn more about the object hierarchy of Excel Visual Basic.
8) Workbook and Worksheet: In this chapter you will learn more about the Excel VBA Workbook and Excel VBA Worksheet object.
You will see that the Worksheet and Workbook object have properties and methods as well, such as the count property which counts the number of active workbooks or worksheets. The Workbook and Worksheet object are commonly used in Excel VBA. They are very useful when your macro code has to be executed on different workbooks or worksheets.
9) Application Object: The mother of all objects is Excel itself. We call it the Application object. The application object gives access to a lot of Excel related options.
7) Objects, Properties and Methods: In this chapter you will learn more about Excel VBA objects. An object has properties and methods. Excel Visual Basic is a semi-object oriented programming language. Learn more about the object hierarchy of Excel Visual Basic.
8) Workbook and Worksheet: In this chapter you will learn more about the Excel VBA Workbook and Excel VBA Worksheet object.
You will see that the Worksheet and Workbook object have properties and methods as well, such as the count property which counts the number of active workbooks or worksheets. The Workbook and Worksheet object are commonly used in Excel VBA. They are very useful when your macro code has to be executed on different workbooks or worksheets.
9) Application Object: The mother of all objects is Excel itself. We call it the Application object. The application object gives access to a lot of Excel related options.
VBA Basics 1:-
This section explains the basics of Excel Visual Basic. It is good to know the basic terminology explained in this section before you start programming in Excel Visual Basic.
1) Macro Security: Setting up your macro security settings correctly is essential to protect yourself against potential viruses. Make sure your macro security settings are set up correctly so no harm can be done to your computer.
2) Visual Basic Editor: Learn how to launch the Visual Basic Editor and get the best configuration of the Project Explorer and the Code Window in your Excel Version. The Visual Basic Editor is the starting point for creating macros in Excel VBA, so it is important to get this configuration right.
3) Macro Comments: Add macro comments to your Excel VBA code and your code will be easier to read as program size increases.
4) MsgBox: The Message Box is a dialog box you can have appear to inform the users of your program.
5) Macro Errors: Dealing with VBA-errors can be quite a challenge. This chapter provides you with a simple tip to deal with these errors.
1) Macro Security: Setting up your macro security settings correctly is essential to protect yourself against potential viruses. Make sure your macro security settings are set up correctly so no harm can be done to your computer.
2) Visual Basic Editor: Learn how to launch the Visual Basic Editor and get the best configuration of the Project Explorer and the Code Window in your Excel Version. The Visual Basic Editor is the starting point for creating macros in Excel VBA, so it is important to get this configuration right.
3) Macro Comments: Add macro comments to your Excel VBA code and your code will be easier to read as program size increases.
4) MsgBox: The Message Box is a dialog box you can have appear to inform the users of your program.
5) Macro Errors: Dealing with VBA-errors can be quite a challenge. This chapter provides you with a simple tip to deal with these errors.
Subscribe to:
Posts (Atom)