SlideShare uma empresa Scribd logo
1 de 27
Baixar para ler offline
Nick Weisenberger 
GETTING STARTED WITH MICROSOFT EXCEL MACROS 
Excel Spreadsheets Help Help
 
A macro is a series of functions written in a programming language that is grouped in a single command to perform the requested task automatically. 
 
Macros use programming but you don't need to be a programmer or have programming knowledge to use them (though it certainly does help). 
 
If you perform a task repeatedly you can take advantage of a macro to automate the task. 
WHAT IS A MACRO?
Macros are used to save time and reduce the possibility of human error by automating repetitive processes. Other reasons for using macros include: 
Standardization 
Improving efficiency 
Expanding Excel's capabilities 
 Streamlining procedures 
WHY USE MACROS?
The application of automation in the design process is virtually unlimited. Some real world examples of Excel automation at work: 
Export to Word, PPT, email, etc. 
Reset a spreadsheet template to blank 
Allows user who has little experience with Excel to do complicated tasks 
Automatically create folders 
Combine multiple workbooks into one 
And so on and so on. The possibilities are nearly limitless. 
MACRO EXAMPLES
Macros within Excel are created by two primary methods: 
 
Using the macro recorder or 
 
Writing custom code with the macro editor 
To view macros in a workbook: 
Go to View tab at top > Macros 
Keyboard shortcut: Alt+F8 
HOW TO CREATE MACROS
 
One method for creating macros is by recording your mouse actions by: 
 
Going to View>Macros>Record Macro 
 
Enter a name then click OK. 
 
Excel is now recording your actions until you click the stop button in the lower left hand corner 
 
DON'T: Record more than is absolutely necessary. 
 
DON'T: Use the UNDO button when recording a macro. 
 
DO: Check each macro after it's recorded. 
 
To view the code that was just recorded go to View>Macros>View Macros > Select the macro then click Step Into to launch the macro editor. 
MACRO RECORDER
 
Many times extra lines of code are added which are not necessary. This is based on the order of steps that you do as you record the macro. These unnecessary lines can be removed. 
 
Recorded macros do not contain any comments or explanations of what is happening in the code and input parameters are never recorded. 
 
Recorded macros are very simple and don’t contain If statements, Loops, or other commonly used code. 
 
Record macros can be used for simple tasks but it is better to write custom code; use the recorder if you get stuck or to find out the syntax if you don’t know it. 
CONS OF MACRO RECORDING
 
To write custom macros you need to know Excel’s programming language, Visual Basic for Applications. 
 
VBA provides a complete programming environment with an editor, debugger, and help object viewer. 
 
Excel cannot run a macro program WITHOUT the host application (Excel) running (meaning it runs as a DLL in the same memory space as the host application). 
 
Excel macros are run in-process, meaning Excel essentially freezes while the macro is running and the allocation memory is wiped clean after each run of the program so passing data between subsequent runs is impossible. 
PROGRAMMING LANGUAGE
 
Syntax is defined as the ordering of and relationship between the words and other structural elements in phrases and sentences. 
 
Each programming language is composed of its own syntax. 
 
Think of it like this: when you see an email address (nick@excelspreadsheetshelp.com) you immediately identify it as an email address. Why is this? An email address has a correct structure in the language of the internet, its syntax. 
 
Syntax enables the programming language to understand what it is you are trying to do 
MACRO SYNTAX
 
Case Sensitivity: By default, VBA is not case sensitive and does not differentiate between upper-case and lower-case spelling of words. 
 
Comments: Add comments to your statements using an apostrophe ('), either at the beginning of a separate line, or at the end of a statement. It is recommended that you add comments wherever possible to make your scripts easier to understand and maintain, especially if another user has to make changes to it later on down the road. 
 
Indentation: Indent or out dent script to reflect the logical structure and nesting of the statements to make it easier to read. 
 
Parentheses: It is important to use parentheses correctly in any statement to achieve the desired result and to avoid errors. 
SYNTAX
 
Semicolon (:): Inserting a semicolon allows you to write multiple commands on the same line of code. 
 
Single Quotation(‘): To return a single quotation mark which does not indicate a comment (needed in a formula for example), you'll have to use the Chr function. Chr() is a built-in VBA function that returns the character that corresponds to the numeric value of its argument using the ASCII coding scheme. If you provide Chr with an integer value (such as 39) it will report back the character that corresponds to that value. The ASCII value of 39 is the single quote mark. Chr(34) is for the double quote mark 
 
Spaces: Add extra blank spaces to your script to improve clarity. These spaces are ignored by VBA. 
SYNTAX
 
Text Strings: When a value is entered as a text string you must add quotation marks before and after the string. 
 
You can concatenate, or combine, multiple strings using a plus (+) or ampersand (&) sign: txtString = “This value is “+ TestValue. Return the left, middle, or right of a string using: left(sting, digits), mid(string, digits), or right(string, digits). Get the complete length of a string with len(string). To figure out if a string contains another string use Instr(). Convert numeric strings and vice versa using str(num) or val(string). 
 
Underscore(_): Carry over to next line (line concatenation symbol). 
SYNTAX
 
When you run your macro program, the code will be read by the computer line by line, generally from top to bottom and from left to right, just like reading a book. 
 
The program flows down the code until it hits a decision point where it may have to jump to a different portion of the program or re-run lines of code that it already read. 
 
The program chooses what lines of code to execute based on the state of the variables you have defined. 
SEQUENTIAL PROGRAMMING
 
The execution of the program depends on an event, such as a user clicking a button with the mouse, an object being selected, certain text or characters being typed into a form, etc. 
 
One common decision point is an If...Else statement. If the variable equals x then do y, else do z. 
 
Another one is the while loop which will execute the lines of code within the loop over and over until the condition becomes false. 
EVENT DRIVEN PROGRAMMING
 
Variables make up the backbone of any programming language. 
 
Variables store information that can be accessed later by referring to a name or “variable.” 
 
Variables can then be declared as a type to let us know what we can do with that information. 
 
The value of a variable will not necessarily be constant throughout the duration a program is running. 
 
Naming variables is important; it’s best to be descriptive i.e. RowNumber, ColumnNumber 
VARIABLES
 
Variable names, also known as identifiers, must be less than 255 characters 
 
They cannot start with a number. 
 
Special characters such as spaces and periods are forbidden. 
 
Avoid naming conflicts; two variables cannot have the same name. 
Example: 
 
Good Variable Names: dimensionOne, dimension1 
 
Bad Variable Names: dimension One, 1dimension 
VARIABLES
There is a popular naming convention where a letter is placed in front of the variable name to notate what type of data the variable is: 
o=object (i.e. oPartDoc) 
s=selection (i.e sSelection1) 
str=string (i.e. strFilename) 
i=integer (i.e iCount) 
rng=Range (i.e. rngField) 
Some programmers use “int” or “n” for integer and “str” for string. Either or works as long as your notation is consistent and easy for others to understand. 
VARIABLES NOTATION
 
By default, Excel doesn’t force you to declare your variables. However, you should change that setting immediately. Press Alt+F11 to launch the Visual Basic Editor (VBE). Go to Tools>Options. 
 
In the Editor tab of the Options dialog, make sure that there’s a check mark in front of “Require Variable Declaration”
 
Now you’ll see Option Explicit as the first line of the module. This tells Excel that all variables must be declared, making our code easier to follow. 
OPTION EXPLICIT
 
Variables are "dimmed" (declared) as a type, either a "primitive" type (single, double, integer, string, etc.) or an object type (more complex). 
 
The "Dim" command is used to allocate a variable of any type. Primitive variables are populated with a value. Declaring variables with a ‘Dim’ statement helps save memory while running the program . 
 
After a variable is declared through dimming then it is “Set” or given a value. 
 
For object variables, the "Set" command is used to "point" the variable to the object. Within the program, the variable then represents that object unless it is "Set" to a different one. 
DIMMING AND SETTING
 
An Excel program or "macro" consists of a "Subroutine“. 
 
Excel only recognizes the Sub ___() as the entry point to any VBA application. 
 
Every Sub must end with an End Sub. 
 
You’ll add your code in-between the subs 
MACRO BASICS
To create your first custom macro: 
 
Use the shortcut Alt+F8 
 
Type in a new macro name “Test” 
 
Click “Create” to launch the macro editor 
 
Add the following code between the subs: 
 
Msgbox “Hello world.” 
 
Click the play button and a message box with the words “Hello world.” should pop up in front of your spreadsheet. 
Option Explicit 
Sub Main() 
MsgBox “Hello world.” 
End Sub 
CREATE A MSGBOX MACRO
 
How often do you find yourself emailing a spreadsheet once you’ve completed it? Eliminate the extra step of opening email, attaching a documents, etc. by sending the spreadsheet directly from Excel via a macro. Here’s an example: 
Sub Email() 
ActiveWorkbook.SendMail recipients:="---@---.com" 
End Sub 
EXAMPLE: EMAIL WORKBOOK
Sometimes you may want to close all files without saving. Doing it manually is a hassle with all the "Do you wanna save?" question pop ups. Here is a simple macro to close all files automatically: 
Sub CloseAll() 
Application.DisplayAlerts = False 
myTotal = Workbooks.Count 
For i = 1 To myTotal 
ActiveWorkbook.Close 
Next i 
End Sub 
EXAMPLE: CLOSE ALL OPEN WORKBOOKS
 
Syntax is often the most frequent cause of a macro program not working and throwing an error. Excel’s VBA editor contains a built-in syntax checker and works much like a grammar checker found in software like Microsoft Word and will even give you hints about what it thinks you meant. 
 
One of the best ways to learn about macros is by looking at and using code that others have written and is proven to work 
 
Use the internet to ask questions: Eng Tips, StackoverFlow, Mr Excel Forum, Contact Me 
TROUBLESHOOTING
Want to learn even more about Excel macros and other tips?
. 
CLICK HERE TO SIGNUP FOR FREE! 
Join the Excel Spreadsheets Help newsletter to receive Excel tips right in your inbox.

Mais conteúdo relacionado

Mais procurados

A Quick Simple MS Excel Macro
A Quick Simple MS Excel MacroA Quick Simple MS Excel Macro
A Quick Simple MS Excel MacroPranav Ghode
 
E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3Vijay Perepa
 
E learning excel vba programming lesson 1
E learning excel vba programming  lesson 1E learning excel vba programming  lesson 1
E learning excel vba programming lesson 1Vijay Perepa
 
visual basic v6 introduction
visual basic v6 introductionvisual basic v6 introduction
visual basic v6 introductionbloodyedge03
 
Advance Excel Training
Advance Excel TrainingAdvance Excel Training
Advance Excel TrainingPriyanka Verma
 
03 Excel formulas and functions
03 Excel formulas and functions03 Excel formulas and functions
03 Excel formulas and functionsBuffalo Seminary
 
Ms excel ppt presentation
Ms excel ppt presentationMs excel ppt presentation
Ms excel ppt presentationvethics
 
Ms excel 2010 Training in Ambala ! Batra Computer Centre
Ms excel 2010 Training in Ambala ! Batra Computer CentreMs excel 2010 Training in Ambala ! Batra Computer Centre
Ms excel 2010 Training in Ambala ! Batra Computer Centrejatin batra
 
Excel VBA programming basics
Excel VBA programming basicsExcel VBA programming basics
Excel VBA programming basicsHang Dong
 
Vb decision making statements
Vb decision making statementsVb decision making statements
Vb decision making statementspragya ratan
 
Visual Programming
Visual ProgrammingVisual Programming
Visual ProgrammingBagzzz
 
Advanced Microsoft Excel
Advanced Microsoft ExcelAdvanced Microsoft Excel
Advanced Microsoft ExcelEric Metelka
 

Mais procurados (20)

A Quick Simple MS Excel Macro
A Quick Simple MS Excel MacroA Quick Simple MS Excel Macro
A Quick Simple MS Excel Macro
 
VBA - Macro For Ms.Excel
VBA - Macro For Ms.ExcelVBA - Macro For Ms.Excel
VBA - Macro For Ms.Excel
 
E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3
 
Excel-VBA
Excel-VBAExcel-VBA
Excel-VBA
 
Ms excel
Ms excelMs excel
Ms excel
 
E learning excel vba programming lesson 1
E learning excel vba programming  lesson 1E learning excel vba programming  lesson 1
E learning excel vba programming lesson 1
 
Excel Macro Magic
Excel Macro MagicExcel Macro Magic
Excel Macro Magic
 
visual basic v6 introduction
visual basic v6 introductionvisual basic v6 introduction
visual basic v6 introduction
 
Advance Excel Training
Advance Excel TrainingAdvance Excel Training
Advance Excel Training
 
Vba
Vba Vba
Vba
 
03 Excel formulas and functions
03 Excel formulas and functions03 Excel formulas and functions
03 Excel formulas and functions
 
Ms excel ppt presentation
Ms excel ppt presentationMs excel ppt presentation
Ms excel ppt presentation
 
Ms excel 2010 Training in Ambala ! Batra Computer Centre
Ms excel 2010 Training in Ambala ! Batra Computer CentreMs excel 2010 Training in Ambala ! Batra Computer Centre
Ms excel 2010 Training in Ambala ! Batra Computer Centre
 
Microsoft word
Microsoft wordMicrosoft word
Microsoft word
 
Excel VBA programming basics
Excel VBA programming basicsExcel VBA programming basics
Excel VBA programming basics
 
Vb decision making statements
Vb decision making statementsVb decision making statements
Vb decision making statements
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
 
Advanced Microsoft Excel
Advanced Microsoft ExcelAdvanced Microsoft Excel
Advanced Microsoft Excel
 
MS Word Introduction and Tools.
MS Word Introduction and Tools.MS Word Introduction and Tools.
MS Word Introduction and Tools.
 
Java script
Java scriptJava script
Java script
 

Semelhante a Getting started with Microsoft Excel Macros

Getting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosGetting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosEmmett Ross
 
Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfacsmadurai
 
How to apply a formula and macro in excel......by irfan afzal
How to apply a formula and macro in excel......by irfan afzalHow to apply a formula and macro in excel......by irfan afzal
How to apply a formula and macro in excel......by irfan afzal1995786
 
Impact of indentation in programming
Impact of indentation in programmingImpact of indentation in programming
Impact of indentation in programmingijpla
 
01 Database Management (re-uploaded)
01 Database Management (re-uploaded)01 Database Management (re-uploaded)
01 Database Management (re-uploaded)bluejayjunior
 
Ppt on visual basics
Ppt on visual basicsPpt on visual basics
Ppt on visual basicsyounganand
 
Vba and macro creation (using excel)
Vba and macro creation (using excel)Vba and macro creation (using excel)
Vba and macro creation (using excel)Javier Morales Cauna
 
Functional programming in TypeScript
Functional programming in TypeScriptFunctional programming in TypeScript
Functional programming in TypeScriptbinDebug WorkSpace
 
Chapter 5( programming) answer
Chapter 5( programming) answerChapter 5( programming) answer
Chapter 5( programming) answersmkengkilili2011
 
Visual basic 6.0
Visual basic 6.0Visual basic 6.0
Visual basic 6.0Aarti P
 
REXX_ Lab_1 ITT 340 NOTE If you are still a little shaky about.docx
REXX_ Lab_1  ITT 340 NOTE If you are still a little shaky about.docxREXX_ Lab_1  ITT 340 NOTE If you are still a little shaky about.docx
REXX_ Lab_1 ITT 340 NOTE If you are still a little shaky about.docxjoellemurphey
 
Inline functions & macros
Inline functions & macrosInline functions & macros
Inline functions & macrosAnand Kumar
 
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)pbarasia
 

Semelhante a Getting started with Microsoft Excel Macros (20)

Getting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosGetting started with CATIA V5 Macros
Getting started with CATIA V5 Macros
 
Vba part 1
Vba part 1Vba part 1
Vba part 1
 
Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdf
 
Vba part 1
Vba part 1Vba part 1
Vba part 1
 
VBA
VBAVBA
VBA
 
How to apply a formula and macro in excel......by irfan afzal
How to apply a formula and macro in excel......by irfan afzalHow to apply a formula and macro in excel......by irfan afzal
How to apply a formula and macro in excel......by irfan afzal
 
Impact of indentation in programming
Impact of indentation in programmingImpact of indentation in programming
Impact of indentation in programming
 
01 Database Management (re-uploaded)
01 Database Management (re-uploaded)01 Database Management (re-uploaded)
01 Database Management (re-uploaded)
 
Ppt on visual basics
Ppt on visual basicsPpt on visual basics
Ppt on visual basics
 
Vba and macro creation (using excel)
Vba and macro creation (using excel)Vba and macro creation (using excel)
Vba and macro creation (using excel)
 
Functional programming in TypeScript
Functional programming in TypeScriptFunctional programming in TypeScript
Functional programming in TypeScript
 
Chapter 5( programming) answer
Chapter 5( programming) answerChapter 5( programming) answer
Chapter 5( programming) answer
 
Visual basic 6.0
Visual basic 6.0Visual basic 6.0
Visual basic 6.0
 
REXX_ Lab_1 ITT 340 NOTE If you are still a little shaky about.docx
REXX_ Lab_1  ITT 340 NOTE If you are still a little shaky about.docxREXX_ Lab_1  ITT 340 NOTE If you are still a little shaky about.docx
REXX_ Lab_1 ITT 340 NOTE If you are still a little shaky about.docx
 
Inline functions & macros
Inline functions & macrosInline functions & macros
Inline functions & macros
 
ArduinoWorkshop2.pdf
ArduinoWorkshop2.pdfArduinoWorkshop2.pdf
ArduinoWorkshop2.pdf
 
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)
 
Java script basic
Java script basicJava script basic
Java script basic
 
X++ 1.pptx
X++ 1.pptxX++ 1.pptx
X++ 1.pptx
 
Matlab-3.pptx
Matlab-3.pptxMatlab-3.pptx
Matlab-3.pptx
 

Mais de Nick Weisenberger

10 Defunct Theme Park Steam Trains
10 Defunct Theme Park Steam Trains10 Defunct Theme Park Steam Trains
10 Defunct Theme Park Steam TrainsNick Weisenberger
 
15 Best Theme Park Steam Trains
15 Best Theme Park Steam Trains15 Best Theme Park Steam Trains
15 Best Theme Park Steam TrainsNick Weisenberger
 
Guess the Roller Coaster Game: Volume 1
Guess the Roller Coaster Game: Volume 1Guess the Roller Coaster Game: Volume 1
Guess the Roller Coaster Game: Volume 1Nick Weisenberger
 
How to Combine text from two or more cells in Excel
How to Combine text from two or more cells in ExcelHow to Combine text from two or more cells in Excel
How to Combine text from two or more cells in ExcelNick Weisenberger
 
Disneyland Guide Summer 1968
Disneyland Guide Summer 1968Disneyland Guide Summer 1968
Disneyland Guide Summer 1968Nick Weisenberger
 
20 Unique Uses of Excel Spreadsheets
20 Unique Uses of Excel Spreadsheets20 Unique Uses of Excel Spreadsheets
20 Unique Uses of Excel SpreadsheetsNick Weisenberger
 

Mais de Nick Weisenberger (8)

Coasters-101: Lift Hills
Coasters-101: Lift HillsCoasters-101: Lift Hills
Coasters-101: Lift Hills
 
10 Defunct Theme Park Steam Trains
10 Defunct Theme Park Steam Trains10 Defunct Theme Park Steam Trains
10 Defunct Theme Park Steam Trains
 
15 Best Theme Park Steam Trains
15 Best Theme Park Steam Trains15 Best Theme Park Steam Trains
15 Best Theme Park Steam Trains
 
Guess the Roller Coaster Game: Volume 1
Guess the Roller Coaster Game: Volume 1Guess the Roller Coaster Game: Volume 1
Guess the Roller Coaster Game: Volume 1
 
How to Combine text from two or more cells in Excel
How to Combine text from two or more cells in ExcelHow to Combine text from two or more cells in Excel
How to Combine text from two or more cells in Excel
 
IAE 2016 Recap
IAE 2016 RecapIAE 2016 Recap
IAE 2016 Recap
 
Disneyland Guide Summer 1968
Disneyland Guide Summer 1968Disneyland Guide Summer 1968
Disneyland Guide Summer 1968
 
20 Unique Uses of Excel Spreadsheets
20 Unique Uses of Excel Spreadsheets20 Unique Uses of Excel Spreadsheets
20 Unique Uses of Excel Spreadsheets
 

Último

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 

Último (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

Getting started with Microsoft Excel Macros

  • 1. Nick Weisenberger GETTING STARTED WITH MICROSOFT EXCEL MACROS Excel Spreadsheets Help Help
  • 2.  A macro is a series of functions written in a programming language that is grouped in a single command to perform the requested task automatically.  Macros use programming but you don't need to be a programmer or have programming knowledge to use them (though it certainly does help).  If you perform a task repeatedly you can take advantage of a macro to automate the task. WHAT IS A MACRO?
  • 3. Macros are used to save time and reduce the possibility of human error by automating repetitive processes. Other reasons for using macros include: Standardization Improving efficiency Expanding Excel's capabilities  Streamlining procedures WHY USE MACROS?
  • 4. The application of automation in the design process is virtually unlimited. Some real world examples of Excel automation at work: Export to Word, PPT, email, etc. Reset a spreadsheet template to blank Allows user who has little experience with Excel to do complicated tasks Automatically create folders Combine multiple workbooks into one And so on and so on. The possibilities are nearly limitless. MACRO EXAMPLES
  • 5. Macros within Excel are created by two primary methods:  Using the macro recorder or  Writing custom code with the macro editor To view macros in a workbook: Go to View tab at top > Macros Keyboard shortcut: Alt+F8 HOW TO CREATE MACROS
  • 6.  One method for creating macros is by recording your mouse actions by:  Going to View>Macros>Record Macro  Enter a name then click OK.  Excel is now recording your actions until you click the stop button in the lower left hand corner  DON'T: Record more than is absolutely necessary.  DON'T: Use the UNDO button when recording a macro.  DO: Check each macro after it's recorded.  To view the code that was just recorded go to View>Macros>View Macros > Select the macro then click Step Into to launch the macro editor. MACRO RECORDER
  • 7.  Many times extra lines of code are added which are not necessary. This is based on the order of steps that you do as you record the macro. These unnecessary lines can be removed.  Recorded macros do not contain any comments or explanations of what is happening in the code and input parameters are never recorded.  Recorded macros are very simple and don’t contain If statements, Loops, or other commonly used code.  Record macros can be used for simple tasks but it is better to write custom code; use the recorder if you get stuck or to find out the syntax if you don’t know it. CONS OF MACRO RECORDING
  • 8.  To write custom macros you need to know Excel’s programming language, Visual Basic for Applications.  VBA provides a complete programming environment with an editor, debugger, and help object viewer.  Excel cannot run a macro program WITHOUT the host application (Excel) running (meaning it runs as a DLL in the same memory space as the host application).  Excel macros are run in-process, meaning Excel essentially freezes while the macro is running and the allocation memory is wiped clean after each run of the program so passing data between subsequent runs is impossible. PROGRAMMING LANGUAGE
  • 9.  Syntax is defined as the ordering of and relationship between the words and other structural elements in phrases and sentences.  Each programming language is composed of its own syntax.  Think of it like this: when you see an email address (nick@excelspreadsheetshelp.com) you immediately identify it as an email address. Why is this? An email address has a correct structure in the language of the internet, its syntax.  Syntax enables the programming language to understand what it is you are trying to do MACRO SYNTAX
  • 10.  Case Sensitivity: By default, VBA is not case sensitive and does not differentiate between upper-case and lower-case spelling of words.  Comments: Add comments to your statements using an apostrophe ('), either at the beginning of a separate line, or at the end of a statement. It is recommended that you add comments wherever possible to make your scripts easier to understand and maintain, especially if another user has to make changes to it later on down the road.  Indentation: Indent or out dent script to reflect the logical structure and nesting of the statements to make it easier to read.  Parentheses: It is important to use parentheses correctly in any statement to achieve the desired result and to avoid errors. SYNTAX
  • 11.  Semicolon (:): Inserting a semicolon allows you to write multiple commands on the same line of code.  Single Quotation(‘): To return a single quotation mark which does not indicate a comment (needed in a formula for example), you'll have to use the Chr function. Chr() is a built-in VBA function that returns the character that corresponds to the numeric value of its argument using the ASCII coding scheme. If you provide Chr with an integer value (such as 39) it will report back the character that corresponds to that value. The ASCII value of 39 is the single quote mark. Chr(34) is for the double quote mark  Spaces: Add extra blank spaces to your script to improve clarity. These spaces are ignored by VBA. SYNTAX
  • 12.  Text Strings: When a value is entered as a text string you must add quotation marks before and after the string.  You can concatenate, or combine, multiple strings using a plus (+) or ampersand (&) sign: txtString = “This value is “+ TestValue. Return the left, middle, or right of a string using: left(sting, digits), mid(string, digits), or right(string, digits). Get the complete length of a string with len(string). To figure out if a string contains another string use Instr(). Convert numeric strings and vice versa using str(num) or val(string).  Underscore(_): Carry over to next line (line concatenation symbol). SYNTAX
  • 13.  When you run your macro program, the code will be read by the computer line by line, generally from top to bottom and from left to right, just like reading a book.  The program flows down the code until it hits a decision point where it may have to jump to a different portion of the program or re-run lines of code that it already read.  The program chooses what lines of code to execute based on the state of the variables you have defined. SEQUENTIAL PROGRAMMING
  • 14.  The execution of the program depends on an event, such as a user clicking a button with the mouse, an object being selected, certain text or characters being typed into a form, etc.  One common decision point is an If...Else statement. If the variable equals x then do y, else do z.  Another one is the while loop which will execute the lines of code within the loop over and over until the condition becomes false. EVENT DRIVEN PROGRAMMING
  • 15.  Variables make up the backbone of any programming language.  Variables store information that can be accessed later by referring to a name or “variable.”  Variables can then be declared as a type to let us know what we can do with that information.  The value of a variable will not necessarily be constant throughout the duration a program is running.  Naming variables is important; it’s best to be descriptive i.e. RowNumber, ColumnNumber VARIABLES
  • 16.  Variable names, also known as identifiers, must be less than 255 characters  They cannot start with a number.  Special characters such as spaces and periods are forbidden.  Avoid naming conflicts; two variables cannot have the same name. Example:  Good Variable Names: dimensionOne, dimension1  Bad Variable Names: dimension One, 1dimension VARIABLES
  • 17. There is a popular naming convention where a letter is placed in front of the variable name to notate what type of data the variable is: o=object (i.e. oPartDoc) s=selection (i.e sSelection1) str=string (i.e. strFilename) i=integer (i.e iCount) rng=Range (i.e. rngField) Some programmers use “int” or “n” for integer and “str” for string. Either or works as long as your notation is consistent and easy for others to understand. VARIABLES NOTATION
  • 18.  By default, Excel doesn’t force you to declare your variables. However, you should change that setting immediately. Press Alt+F11 to launch the Visual Basic Editor (VBE). Go to Tools>Options.  In the Editor tab of the Options dialog, make sure that there’s a check mark in front of “Require Variable Declaration”
  • 19.  Now you’ll see Option Explicit as the first line of the module. This tells Excel that all variables must be declared, making our code easier to follow. OPTION EXPLICIT
  • 20.  Variables are "dimmed" (declared) as a type, either a "primitive" type (single, double, integer, string, etc.) or an object type (more complex).  The "Dim" command is used to allocate a variable of any type. Primitive variables are populated with a value. Declaring variables with a ‘Dim’ statement helps save memory while running the program .  After a variable is declared through dimming then it is “Set” or given a value.  For object variables, the "Set" command is used to "point" the variable to the object. Within the program, the variable then represents that object unless it is "Set" to a different one. DIMMING AND SETTING
  • 21.  An Excel program or "macro" consists of a "Subroutine“.  Excel only recognizes the Sub ___() as the entry point to any VBA application.  Every Sub must end with an End Sub.  You’ll add your code in-between the subs MACRO BASICS
  • 22. To create your first custom macro:  Use the shortcut Alt+F8  Type in a new macro name “Test”  Click “Create” to launch the macro editor  Add the following code between the subs:  Msgbox “Hello world.”  Click the play button and a message box with the words “Hello world.” should pop up in front of your spreadsheet. Option Explicit Sub Main() MsgBox “Hello world.” End Sub CREATE A MSGBOX MACRO
  • 23.  How often do you find yourself emailing a spreadsheet once you’ve completed it? Eliminate the extra step of opening email, attaching a documents, etc. by sending the spreadsheet directly from Excel via a macro. Here’s an example: Sub Email() ActiveWorkbook.SendMail recipients:="---@---.com" End Sub EXAMPLE: EMAIL WORKBOOK
  • 24. Sometimes you may want to close all files without saving. Doing it manually is a hassle with all the "Do you wanna save?" question pop ups. Here is a simple macro to close all files automatically: Sub CloseAll() Application.DisplayAlerts = False myTotal = Workbooks.Count For i = 1 To myTotal ActiveWorkbook.Close Next i End Sub EXAMPLE: CLOSE ALL OPEN WORKBOOKS
  • 25.  Syntax is often the most frequent cause of a macro program not working and throwing an error. Excel’s VBA editor contains a built-in syntax checker and works much like a grammar checker found in software like Microsoft Word and will even give you hints about what it thinks you meant.  One of the best ways to learn about macros is by looking at and using code that others have written and is proven to work  Use the internet to ask questions: Eng Tips, StackoverFlow, Mr Excel Forum, Contact Me TROUBLESHOOTING
  • 26. Want to learn even more about Excel macros and other tips?
  • 27. . CLICK HERE TO SIGNUP FOR FREE! Join the Excel Spreadsheets Help newsletter to receive Excel tips right in your inbox.