7
Macroguide.blogspot.com Page 1 This 7 Page Tutorial Will Inpsire to Write Your Own Macros in Excel...Read on Macros are another extremely powerful feature of Microsoft office technology which are available in Ms-Office implementations of different OS (including MS -Office for Mac). In this blogspot I will explain effective macro writing using some simple easy-to understand steps. VBA: Visual Basis For Application is an implementation of Microsoft's event driven programming language VB6. So when we are writing a macro we are basically using VB6 programming syntax. If you're not familiar with any programming language, don't worry - we will go step by step here. Five Most Important Points: For writing a macro effectively, we need to understand the four basic syntaxes which are used in most of the computer programming languages - 1. Variables : variables are in simplest from, used to store temporary data throughout the lifecycle of your program. Programming languages can be strongly - typed or weekly-typed. In a strongly typed programming language we must tell the compiler (or the computer) that a particular variable are supposed to handle which type of data. e.g. Int a - here we are telling the computer that a is a variable which should only hold integer type of values. VBA is not a strongly type language - so for writing macro, we can use a variable to hold any type of data. 2. Cells and Sheets: Almost in all occasions when writing a macro we have to read or write into the cells. A particular cell is determined by a two dimensional value, the x - axis value or the rows and the y- axis value or the columns. Cells(x,y).Value - this statement denotes the value of the xth row and the yth column value in any particular worksheet. This can be confusing for some beginners as the columns in any excel sheet is denoted by letters like A,B,C,D etc. Actually, A,B,C in the columns can be denoted in the macro as 1,2,3 etc. So to get the value from the highlighted cell, we can use this statement - Cells(8,3).Value. Now, what if our excel workbook has multiple sheets and we need to see if the value in Cells(3,3) in two different worksheets are same or not? This is what we can do - If Sheets("Sheet1").Cells(3,3).Value= Sheets("Sheet2").Cells(3,3).Value Then MsgBox ("Match Found") End if 3. Conditional Statements: Many occasions our program need to certain actions based on certain conditions. For example, if the excel's cell is empty then show a message to the user. How do we cope with this kind of scenario? we write what is called a conditional statement. Most commonly use from of a conditional statement

Excel Macro in 1 day- beginner's guide

Embed Size (px)

DESCRIPTION

This 7 page tutorial will take you through the programming angle of Excel macro through 5 basic steps with a live example.

Citation preview

Page 1: Excel Macro in 1 day- beginner's guide

Macroguide.blogspot.com Page 1

This 7 Page Tutorial Will Inpsire to Write Your Own Macros in Excel...Read on

Macros are another extremely powerful feature of Microsoft office technology which are available in Ms-Office implementations of different OS (including MS -Office for Mac).

In this blogspot I will explain effective macro writing using some simple easy-to understand steps.

VBA: Visual Basis For Application is an implementation of Microsoft's event driven programming language VB6.So when we are writing a macro we are basically using VB6 programming syntax. If you're not familiar with any programming language, don't worry - we will go step by step here.

Five Most Important Points: For writing a macro effectively, we need to understand the four basic syntaxes which are used in most of the computer programming languages -

1. Variables : variables are in simplest from, used to store temporary data throughout the lifecycle of your program. Programming languages can be strongly - typed or weekly-typed. In a strongly typed programming language we must tell the compiler (or the computer) that a particular variable are supposed to handle which type of data. e.g. Int a - here we are telling the computer that a is a variable which should only hold integer type of values. VBA is not a strongly type language - so for writing macro, we can use a variable to hold any type of data.

2. Cells and Sheets: Almost in all occasions when writing a macro we have to read or write into the cells. A particular cell is determined by a two dimensional value, the x - axis value or the rows and the y-axis value or the columns. Cells(x,y).Value - this statement denotes the value of the xth row and the yth column value in any particular worksheet. This can be confusing for some beginners as the columns in any excel sheet is denoted by letters like A,B,C,D etc. Actually, A,B,C in the columns can be denoted in the macro as 1,2,3 etc. So to get the value from the highlighted cell, we can use this statement -

Cells(8,3).Value.

Now, what if our excel workbook has multiple sheets and we need to see if the value in Cells(3,3) in two different worksheets are same or not?

This is what we can do - If Sheets("Sheet1").Cells(3,3).Value= Sheets("Sheet2").Cells(3,3).Value Then MsgBox ("Match Found") End if

3. Conditional Statements: Many occasions our program need to certain actions based on certain conditions. For example, if the excel's cell is empty then show a message to the user. How do we cope with this kind of scenario? we write what is called a conditional statement. Most commonly use from of a conditional statement

Page 2: Excel Macro in 1 day- beginner's guide

Macroguide.blogspot.com Page 2

is if- else. In the following example, we check the value in the cell (A,2) and the keyword vbNullString denotes whether the cell value is empty or not. MsgBox is the popup control which will display the message.

If Cells(A,2).Value = vbNullString ThenMsgBox (" This cell is empty")ElseMsgBox ("This cell is not empty")End if

See the structure of the if- then - else - end if closely , as you will be using it very often in writing a macro. An if statement must have the condition check in it (in our case Cells (A,2).Value= vbNullString) followed by then. If you wish to write any specific action when the if condition is not met, use an else block. In any case, the if block must be closed with an End If statement. We will see more examples of if- else later in this tutorial.

4. Loops: Loops are what the name suggests and is used for doing similar actions multiple times. Loops are essential parts of any programming language and you will need to use the art of looping for writing a powerful macro. There are different types of loops available in macro writing, but most commonly used loops are for loop and the do- while loop. Let's see an example.

We want to read 10 rows in an excel sheet and check if any of the cell is empty. If its empty we will put the word "N/A" in the cell. Here is how we can do it.

i=1j=1

For i=1 to 10

If Cells(i,j).Value = vbNullString ThenCells(i,j).Value="N/A"End if

Next i

At the begining here I have defined two variable i and j which are set to 1. Then we start looping using the for loop. The for loop looks like this -for <start condition> to <end condition>Next <variable name>So, in this example the loop goes on starting with value 1 till 10 for the variable i. The ending next statement keeps incrementing the value of i till it hits the end-condition value which is 10 in this case. In each occurances inside the loop, the if statement checks if the cell value is empty, if empty then overwrite the cell with the string "N/A".

5. Functions and Subrounties: In programming jargon, code- reusability is a major consideration since the inception of the first programming language. The idea is to write once - use everywhere as required. Simply put, you write a small piece of code which does a specific work (say multiple two numbers) and you want to use it in many places whenever you need to multiply two numbers. Instead of writing the same code everywhere, you put the code in a function and just call the function as required.The difference between a function and a subroutine is that a function can return a value whereas a subroutine can not.Lets see an example -

Page 3: Excel Macro in 1 day- beginner's guide

Macroguide.blogspot.com Page 3

Function Mul(a,b) as IntegerMul=a * bEnd Funtion

Sub calculate()

firstNumber= Sheets("Sheet1").Cells (2,3).ValuesecNumber=Sheets("Sheet1").Cells (3,3).Value

finalProduct= Mul(firstNumber,secNumber)MsgBox finalProduct

End Sub

Here I am defining a function named Mul which takes two parameters a and b and returns an integer value. The return value needs to be assigned to the name of the function -Mul= a * b. So whoever calls this function with two integer values gets a product of a and b.

The subroutine calculate reads the two numbers from two different cells in Sheet1.Then it calls the function with these two numbers - Mul(firstNumber,secNumber). The function returns the multiplied value and the value is assigned to the variable finalProduct.

Finally the value is displayed in a messagebox .

Our First Full-fledged Macro - Now that we have seen the basics required to write a macro lets go explore our first macro.

Our first macro is a employee database scanner. Here in one sheet of our workbook, we will store a database of employee records with employee id, name, department, age, sex.The requirement is, in another sheet there will be a textbox and a button. Whenever an employee id is entered into that textbox and the button is pressed, our macro will search the database and return the details of the employee.

Insert the button using the form control as shown in this screenshot –

After selecting the button it can be placed in any of the cells of your choice. At this point, excel will ask you associate the button to a macro - you can give a name of your macro and it will be assigned to this button. So whenever the user clicks this button, the given macro will be triggered.

Page 4: Excel Macro in 1 day- beginner's guide

Macroguide.blogspot.com Page 4

Note that, we can later at any stage re-assign a different macro to this button as well.

In our example, we will name the macro as Search.

Now, we populate some data in our second sheet and let's name this sheet as Data.

Do some styling on the first page to display the result and now the workbook looks like this –

Page 5: Excel Macro in 1 day- beginner's guide

Macroguide.blogspot.com Page 5

Now, right click on the button to go to the macro and click new-

It will take you to the code-editor and create an empty subroutine by the name Search –

Here onwards we start writing the macro using the knowledge what we have learned so far in this tutorial.

Here is the macro which will do this job. The green colored lines are comments added for more clarity of the code. Adding comments can be pretty useful when you have a large piece of code and meaningful comments increases the code's readability. Any line starting with a single quote will be considered as a comment by excel.

Page 6: Excel Macro in 1 day- beginner's guide

Macroguide.blogspot.com Page 6

As a good coding practice we should always check if the user enters some invalid data. Here the macro will pop up a message if the id entered is empty –

If the id entered is found then the macro will pull up the result –

Page 7: Excel Macro in 1 day- beginner's guide

Macroguide.blogspot.com Page 7

Final Note: Always remember to save a workbook with macro in excel macro enabled workbook format -

That's all for today. Watch out this place for more upcoming tutorials about macro where we cover some more complicated chapters in macro writing. Feel free to post your comment here.