Basics of Macro
Basics of Macro
14/11/2016
SF-CHN-STM-BANK-ASU-SYSTLIDS
Assurance
[email protected]
Confidentiality Statement
Confidentiality and Non-Disclosure Notice
The information contained in this document is confidential and proprietary to TATA
Consultancy Services. This information may not be disclosed, duplicated or used for
any other purposes. The information contained in this document may not be
released in whole or in part outside TCS for any purpose without the express written
permission of TATA Consultancy Services.
2
Table of Content
1. VBA - Introduction..................................................................................................................................................... 4
2. How to Record Macro in excel .................................................................................................................................. 4
3. Start Scripting ............................................................................................................................................................ 7
4. Message & Input Box ................................................................................................................................................ 8
4.1 Message Box ..................................................................................................................................................... 8
4.2 Input Box ........................................................................................................................................................... 8
5. Comments & Variables ............................................................................................................................................. 9
5.1 Comments ......................................................................................................................................................... 9
5.2 Example ............................................................................................................................................................. 9
6. Decision Making ...................................................................................................................................................... 10
a. Example for Simple if statement ......................................................................................................................... 10
b. Example for if.. else Statement ........................................................................................................................... 10
c. Example for If.. else if.. else Statement .............................................................................................................. 11
7. Looping .................................................................................................................................................................... 12
8. String Functions ...................................................................................................................................................... 13
9. Date & Time Function ............................................................................................................................................. 14
10. Array .................................................................................................................................................................... 15
11. Functions & Sub .................................................................................................................................................. 16
12. Workbook & Worksheet Events.......................................................................................................................... 16
13. Excel Objects ....................................................................................................................................................... 17
3
1. VBA - Introduction
VBA stands for Visual Basic for Applications an event driven programming language from Microsoft
that is now predominantly used with Microsoft office applications such as MS-Excel, MS-Word and MS-
Access. Macro - Macros are used to automate simple, repetitive tasks, which will save hours. Marcos in
Excel are written in Excel VBA. In MS Excel, we have both recording and writing our own macros based on
our need
4
You can give the location, where you want to store this particular macro and also you can write
some description about this particular to be recorded Macro
Now click OK and do some operation on the excel sheet. Like formatting of the cell or sorting some
of the values etc. and click on the Stop button at the same place when you started running the
Macro
To view this particular recorded macro, right click on any of the Sheet Name -> View Code
In left hand side pane, under VBA Project of that workbook, Expand the Module
One Module would have been created in the name “Module 1”. Click on that, you can see the
recorded code with the given Macro Name
5
To run this Macro, delete the formatting done during the recording of this macro. Now once we will
run this Macro, then automatically that formatting will be done in that Sheet
You can run this Recorded Macro in two ways: 1. By Pressing Run Button 2. By Pressing Alt+F8
Now Click on the Run Button. After running the Macro, See the Result
6
3. Start Scripting
We can start scripting by adding a button. Click 'Insert' >> Select 'button‘
Perform Right click on the button and choose ‘Properties’ to edit Name & Caption of the button
Double click the button, the sub procedure outline would be displayed as shown below
Start the coding by simply adding a message box
8
5. Comments & Variables
5.1 Comments
A macro comment is a piece of text in a macro which will not be executed by Excel VBA. It is
only there to provide you information about the macro
‘Get Input from User
5.2 Example
A Variable is a small chunk of computer’s memory used to store a value. Commonly used
Variable are listed below
Visual Basic
Storage Allocation Value Range
Type
Depends on
True or False
Boolean implementing platform
Char (single
2 bytes 0 through 65535 (unsigned)
character)
String
Depends on
(variable- 0 to approximately 2 billion Unicode characters
implementing platform
length)
9
6. Decision Making
Decision making allows programmers to control the execution flow of a script. The execution is governed by
one or more conditional statements
Statement Description
An if statement consists of a boolean expression followed by one or
if statement more statements.
An if else statement consists of a boolean expression followed by one
or more statements. If the condition is True, the statements under If
statements are executed. If the condition is false, Else part of the script
if..else statement is Executed
If a = “Green" Then
MsgBox a
End If
10
c. Example for If.. else if.. else Statement
a = “Green"
If a = “Green" Then
MsgBox "If statement is executed"
Else If a = “Blue" Then
MsgBox "else if statement is executed"
Else
MsgBox "Else statement is executed"
End If
11
7. Looping
Looping is one of the most powerful programming techniques. A Loop is a set of instructions meant to
be followed certain number of times
12
8. String Functions
String functions are the functions that either return a text string or have at least one text string as an
argument. Listed below are few String Functions
Function Description
LCase Returns a string or character converted to lowercase.
UCase Returns a string or character containing the specified string converted to uppercase.
Left Returns a string containing a specified number of characters from the left side of a string.
Right Returns a string containing a specified number of characters from the right side of a string.
LTrim Returns a string containing a copy of a specified string with no leading spaces.
RTrim Returns a string containing a copy of a specified string with no trailing spaces.
Len Returns an integer that contains the number of characters in a string.
Trim Returns a string containing a copy of a specified string with no leading or trailing spaces.
Mid Returns a string containing a specified number of characters from a string.
Join Returns a string created by joining a number of substrings contained in an array.
Returns a string in which a specified substring has been replaced with another substring a specified
Replace number of times
Space Returns a string consisting of the specified number of spaces.
13
9. Date & Time Function
Date and Time Functions help the developers to convert date and time from one format to another or to
express the date or time value in the format that suits a specific condition.
Function Description
Date It returns the current system date
CDate It converts a given input to Date
IsDate It returns a Boolean Value whether or not the supplied parameter is a date
Day It returns an integer between 1 and 31 that represents the day of the specified Date
Month It an integer between 1 and 12 that represents the month of the specified Date
Year It returns an integer that represents the year of the specified Date
MonthName It returns Name of the particular month for the specifed date
WeekDayName It returns the weekday name for the specified day.
Now It returns the current system date and Time
Hour It returns an integer between 0 and 23 that represents the Hour part of the the given time
Minute It returns an integer between 0 and 59 that represents the Minutes part of the the given time
Second It returns an integer between 0 and 59 that represents the Seconds part of the the given time
Time It returns the current system time
14
10. Array
Array is series of values that stored in a single variable. Array Declaration is same way a variable has
been declared except that the declaration of an array variable uses parenthesis
Dim arr1() 'Without Size
Dim arr2(5) 'Declared with size of 5
Dim arr3 arr3 = Array("apple","Orange","Grapes")
Although, the Array size is indicated as 5, it can hold 6 values as array index starts from ZERO.
Array Index Cannot be Negative. Assigning Values to the array is by specifying array index value against
each one of the values to be assigned
Dim arr(2)
arr(0) = "1" 'Number as String
arr(1) = "VBScript" 'String
arr(2) = 100 'Number
Arrays are not just limited to single dimension and can have a maximum of 60 dimensions. Two-
dimension arrays are the most commonly used ones
Dim arr(2,2) as Variant ' Which has 3 rows and 3 columns arr(0,0) = "Apple“
arr(0,1) = "Orange"
arr(0,2) = "Grapes"
arr(1,0) = "cucumber"
arr(1,1) = "beans"
arr(1,2) = "carrot"
15
11. Functions & Sub
a. Functions
A function is a group of reusable code which can be called anywhere in your program
Functions are always enclosed within Function and End Function
Function Area(x As Double, y As Double) As Double
Area = x * y
End Function
b. Sub
Sub Procedures are similar to functions but there are few differences
Sub procedures DONOT Return a value while functions may or may not return a value
Sub procedures are always enclosed within Sub and End Sub statements
16
13. Excel Objects
a. Workbook Objects
Woorkbooks.close
Workbooks.add
Workbooks.Open FileName:="Test.xls", ReadOnly:=True
Workbooks("Test.xls").Worksheets("Sheet1").Activate
b. Worksheet Objects
Worksheet(1).visible=true
Worksheets("Sheet1").Protect password:=strPassword, scenarios:=True
c. Range Objects
Worksheets("Sheet1").Range("A5").Value = "5235"
Worksheets("Sheet1").Range("A1:A4").Value = 5
17
Thank You
Contact
IT Services
Business Solutions
Consulting
All content / information present here is the exclusive property of Tata Consultancy Services Limited (TCS). The content /
information contained here is correct at the time of publishing. No material from here may be copied, modified,
reproduced, republished, uploaded, transmitted, posted or distributed in any form without prior written permission from
TCS. Unauthorized use of the content / information appearing here may violate copyright, trademark and other applicable
laws, and could result in criminal or civil penalties. Copyright © 2011 Tata Consultancy Services Limited
18