I was going through an Excel-VBA book and found very interesting stuff. They were not so jazzy and cool as VBA programming but, still, it would be good if we know them. I was confused with the title of this blog. Title of the chapter was "Getting Started". I thought the content was an amalgamation of Best Practice and Tips & Tricks. Hence, I thought to keep the title as "Getting Started, Tips and Tricks, Best Practices". I hope and expect the content justifies the title. Without wasting your precious time and testing your patience further, let me come to the point. Here, I go
- Procedures and functions should be declared in the module.
- 'Option Explicit' directive makes sure that you declare a variable before you use it.
- Always define a variable. This saves memory as well as prevents errors.
- Object variable such as object, range, workbook, worksheet etc do not store anything. They point to something like range, workbook, worksheet. "Set" is the keyword to initialize Object Variable.
- VBA editor has something very intelligent built into it. Type initial few letters of variables and press CTRL+Space. This will display a list of variables starting with those few typed letters. Very useful, in case your VBA code is very big and you have defined tons of variables.
- Might be trivial but it deserves a reference. VBA has built in constants. They are prefixed with vb, xl or mso. Example: vbBlue, XlRight, XlUp
- Unlike Msgbox, Inputbox takes an input from the user. Format or Syntax of InputBox is D=inputbox(Message, title of input box)
- Sometimes we use parenthesis sometimes we do not. Example is Msgbox function. msgbox "Name " &NAME, vbok, "NAME Of Student" and msgbox "Name " &NAME, vbok, "NAME Of Student" will produce same output.Parenthesis are used when we require to capture the result of the action.
- VBA is not allowed to use functions with similar functionality from excel using worksheetfucntion. Surprised, but it is true.
- Sometime we specify a method which requires (an) argument(s). Following piece of code Range("A1:A10").copy destination:=range("D1:D10") will do copy & paste operation in VBA. Here, destination is the argument and Range D1:D10 is value of the argument. Hence, what follows := in such methods are values of argument (preceding :=).
- To prevent screen update during VBA code execution, use Application.ScreenUpdating = False.
- When we try to delete a sheet, Excel pops out an alert message. To prevent such alert messages use Application.DisplayAlerts=False.
- Array size cannot be variable. Excel VBA provides a way to cheat this. Consider following piece of code. Dim A() as integer:var=inputbox("get the size"):redim A(var) . This will redefine array variable A with size as var.
Happy VBAing