1. Avoid Selecting Objects
Avoid selecting an object to change its properties or execute its methods.
For example, you may want to enter some at Range D3, and you can write the code as shown below:
Range("D3").Select
Selection.Value=25
What is the problem with this method?
Think that you have written code to enter 100 values like this (may be using for loop). What if, you press an arrow key while executing the macro? This will change the selection, right? And you know what will happen next (this will write the data into wrong Cell)
This is a simple case, but we deal with ranges, sheets, charts and other objects while writing the codes to automate a task. This can cause serious issues sometimes while automating bigger tasks.
So, always avoid selecting an object (if possible) and directly deal with original object. This will be more accurate and faster.
The same code can be, optimized and written in a single statement as shown below:
Range("D3").Value=25
Background: Many people starts learning VBA using Recording Macros, even I used to record macros and tried to change the code as per the project requirement.
When you record a macro, it will start capturing every action which you are performing on a workbook or worksheet and produce the code/macro. Check the following macro:
Sub entervalue()
'
' entervalue Macro
'
Range("D3").Select
ActiveCell.FormulaR1C1 = "Hi"
Range("D4").Select
End Sub
Most beginners use the same codes while automating the tasks. So, if you are recording the macros to generate the code, please optimize the code before you use.
Leave A Comment