0% found this document useful (0 votes)
8 views

Basics of Macro

Uploaded by

Ganesh Choudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Basics of Macro

Uploaded by

Ganesh Choudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Excel Macro

14/11/2016

SF-CHN-STM-BANK-ASU-SYSTLIDS

Assurance

Srinivasa Prabhuagaran Kannan


758459
Insurance

[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.

Tata Code of Conduct


We, in our dealings, are self-regulated by a Code of Conduct as enshrined in the
Tata Code of Conduct. We request your support in helping us adhere to the Code in
letter and spirit. We request that any violation or potential violation of the Code by
any person be promptly brought to the notice of the Local Ethics Counselor or the
Principal Ethics Counselor or the CEO of TCS. All communication received in this
regard will be treated and kept as confidential.

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

2. How to Record Macro in excel


 To get ‘Developer’ tab in excel, Click on File  Options  Customize Ribbon and check the
Developer Check box. Click OK

 Click on “Record Macro” button in Developer tab


 In Excel 2007 and 2010, Macro recording can be started by clicking on the Red Shape button
marked in the bottom bar of the Excel in left hand side
 Enter the suitable name for the Macro. You can also specify the shortcut key for running this
particular recorded macro. It means on pressing that particular shortcut-key, this macro will run
automatically

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

 Click on Run button to execute the code


 Output will be displayed in a message box with the Text “Hello All”
4. Message & Input Box

4.1 Message Box


It is a dialog box used to inform the users of your program
Msgbox “Hello All”

4.2 Input Box


It displays a prompt in a dialog box, waits for the user to input text or click a button, and then returns
a string containing the contents of the text box
getdate = InputBox("Enter the Date(MM/DD) for generating the Report")

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)

0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on


8 bytes
Date December 31, 9999

0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-


7.9...E+28) † with no decimal point; 0 through +/-
16 bytes
7.9228162514264337593543950335 with 28 places to the right of
Decimal the decimal;

-1.79769313486231570E+308 through -4.94065645841246544E-


8 bytes
Double) 324 † for negative values;

Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed)

Long (long -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807


8 bytes
integer) (9.2...E+18 †) (signed)

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

An if statement followed by one or more ElseIf Statements, that


consists of boolean expressions and then followed by an optional else
statement, which executes when all the condition becomes false.
if...elseif..else statement

An if or elseif statement inside another if or elseif statement(s).


nested if statements
A switch statement allows a variable to be tested for equality against a
Select statement list of values.

a. Example for Simple if statement


a = “Green"

If a = “Green" Then

MsgBox a

End If

b. Example for if.. else Statement


a=“Green"
If a = “Green" Then
MsgBox "If statement is executed"
Else
MsgBox "Else statement is executed"
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

d. Example for nested if Statement


a = “Green"
If a = “Green" Then
MsgBox "If statement is executed"
Else If a = “Blue" Then
MsgBox "else if statement is executed"
b = "Macro"
If b = "Macro" Then
MsgBox "nested if Statement is executing"
End If
Else
MsgBox "Else statement is executing"
End If
e. Example for Select Statement
todayday = "ASD"
Select Case todayday
Case "Friday"
MsgBox "Case 1 is executing"
Case "Thursday"
MsgBox "Case 2 is executing"
Case Else
MsgBox "Default case is executing"
End Select

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

For Loop Do Until Loop Do While Loop


For ... Next loop uses a variable, Do Until loop is very similar to Do While loop repeatedly
which is set to a series of values the Do While loop. The loop executes a section of code while
within a specified range. The repeatedly executes a section a specified condition continues
VBA code inside the loop is then of code until a specified to evaluate to True
executed for each value condition evaluates to True

For i = 1 To 10 i=1 i=1


Total = Total + 1
Do Until i<=10 Do While i<=10
Next i
Msgbox i i=i+1
Loop
Msgbox i
Loop

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.

Split Returns a zero-based, one-dimensional array containing a specified number of substrings.


StrComp Returns -1, 0, or 1, based on the result of a string comparison.
StrConv Returns a string converted as specified.
StrReverse Returns a string in which the character order of a specified string is reversed.

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

12. Workbook & Worksheet Events


Worksheet events are triggered when there is a change in the worksheet
Activate()
Before Double Click
Before Right Click
Calculate
Change
Deactivate
Selection change
Before close
Before print
Before save
Deactivate
New sheet
Open
Window resize

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

For more information, contact [email protected]

About Tata Consultancy Services (TCS)

Tata Consultancy Services is an IT services, consulting and business solutions


organization that delivers real results to global business, ensuring a level of certainty no
other firm can match. TCS offers a consulting-led, integrated portfolio of IT and IT-
enabled infrastructure, engineering and assurance services. This is delivered through its
unique Global Network Delivery ModelTM, recognized as the benchmark of excellence in
software development. A part of the Tata Group, India’s largest industrial conglomerate,
TCS has a global footprint and is listed on the National Stock Exchange and Bombay
Stock Exchange in India.

For more information, visit us at www.tcs.com.

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

You might also like