Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
What we learned in                             1 st    Session1. VBA is EVENT DRIVEN LANGUAGE2. OBJECT-BASED LANGUAGE3. Wh...
How to Create ModulesTo create a new general purposemodule you can use the Insert ->Module option from the VBE menutoolbar...
How to Create Modules..contd…There’s no rule for naming modules except that they must start with an alphacharacter and can...
How to Create Modules..contd…                                                       Workbook Events                       ...
How to Create Modules..contd…If you use the left pull-down of the workbook’s code module you’ll see that there isa specifi...
How to Create Modules..contd…WORKSHEET CODE MODULESThere is one and only one code module per worksheet that is associated ...
For worksheets, when you choose the Worksheet item in the left pulldown list, thedefault event is the Worksheet_SelectionC...
The ‘Target’ and ‘Cancel’ ObjectsOften in worksheet event stubs provided by the VBE you will see reference to twospecial o...
Procedures: Function and SubCode modules contain code, and that code is placed into procedures, andprocedures fall into tw...
SUBSSub procedures are just like Functions, except that they do not return avalue in the same way that a Function does. Th...
VBA Function Procedure ExampleThe word Macro is slang for the word VBA procedure.• A procedure is defined as a named group...
What is a VBA Procedure? Contd..• A VBA procedure unit or block consists of a procedure statement (Sub or Function) and an...
Sub ProceduresSub procedures are written when you want to command Excel like creating achart, analyzing data, coloring cel...
In this example, you create an Excel macrothat converts selected formulas to theircurrent values. Sure, you can do thiswit...
Here comes the hands-on part. Follow these instructions carefully:1. Select the range of cells that contains your formulas...
Upcoming SlideShare
Loading in …5
×

E learning excel vba programming lesson 2

4,554 views

Published on

Excel VBA Programming is not rocket science , just need to understand basics...! Here is the presentation for you!!

Published in: Education, Technology

E learning excel vba programming lesson 2

  1. 1. What we learned in 1 st Session1. VBA is EVENT DRIVEN LANGUAGE2. OBJECT-BASED LANGUAGE3. What is IDE ( Integrated Development Environmetn)4. How to go to VBA IDE5. Various Features of IDE - VBE Menu - Project Window - Code Window - Properties Window - Immediate Window6. Option Explicit - Why Option Explicit - How to set Auto for Option Explicit7. Code Modules - General Purpose Code Modules - Work Book Code Modules - Work Sheet Code Modules Ameetz.com
  2. 2. How to Create ModulesTo create a new general purposemodule you can use the Insert ->Module option from the VBE menutoolbar:After inserting the first new general purpose module, you’llhave a new entry in the VBAProject window. Now you havea new collection called Modules and the new module youjust created will be listed as one of the members of thecollection.Any more modules you add will be listed as new members of the collection. You candouble-click on any of them and view its contents in the Code Window. The oneproperty that a module has is its Name. You can give more meaningful names thanjust “Module1” or “Module2” by changing the name in the properties window whilethe module is the current object of affection active object. Ameetz.com
  3. 3. How to Create Modules..contd…There’s no rule for naming modules except that they must start with an alphacharacter and cant contain certain special characters, I like to give mine namesthat start with “atz” (for ameetz) followed by some description of the use of thecode within them. Examples might be names like:atzUtilities , atzDeclarations , atzOps_OperationsThere is no practical limit to the number of modules. The maximum size of anyindividual module is 64K. However we can insert lot of coding into one modulehence there will be memory limit issues. Ameetz.com
  4. 4. How to Create Modules..contd… Workbook Events Just what are the workbook events? You can get a complete list of them from the code window while theThere is one and only one code module per workbook Workbook Code modulethat is associated with Workbook Event handling. At content is displayed: Youthe technical level, this module, along with the can display that content byworksheet event handling modules are Class Modules. double-clicking theThat need not concern you. Just be aware that if you ThisWorkbook object in thewant to do any coding that deals with events that VBAProject window. You’lloccur at the workbook level, you do it in this get a display similar tomodule. above picture Ameetz.com
  5. 5. How to Create Modules..contd…If you use the left pull-down of the workbook’s code module you’ll see that there isa specific Workbook entry. If you choose that item, the VBE will automatically inserta stub (just the beginning declaration and end statement for the procedure) for theWorkbook_Open() event. You can delete that entry if you don’t need code to deal with something you want to happen when the workbook is opened. With your cursor placed inside of any Workbook related procedure, even just a stub, you can then use the pull-down on the right to find a list of all the available event handlers for the workbook, as shown below : NOTE: If the cursor is not in a workbook event handling procedure, the list on the right will show you a list of non-workbook event procedure names in the module. Ameetz.com
  6. 6. How to Create Modules..contd…WORKSHEET CODE MODULESThere is one and only one code module per worksheet that is associated with WorksheetEvent handling. However, each sheet has its very own code module that is separate anddistinct from all of the others even though they may all have event for a given event forthose worksheets. At the technical level, this module, just like the event handling module forthe workbook are Class Modules. Remember that if you want to do any coding that dealswith events that occur at the worksheet level, you do it in these modules.Worksheet EventsJust what are the worksheet events? You can get a complete list of them from the codewindow while any Worksheet Code module content is displayed: You can display thatcontent by double-clicking any worksheet object in the VBAProject window. The codemodule for that sheet will be displayed as given below: Ameetz.com
  7. 7. For worksheets, when you choose the Worksheet item in the left pulldown list, thedefault event is the Worksheet_SelectionChange(ByVal Target As Range) event.This even triggers any time you make a new selection on the sheet – such assimply moving to another cell. The new cell becomes the selection, and thus you’vehad a selection change.As with the Workbook events, you can now get a complete list of Worksheet Eventsavailable to be programmed against by using the right-side pull-down (indicated as“(Declarations)”). This list is much shorter than the Workbook’s list, as there are 9events (from Excel 2003) provide considerable versatility in dealing withworksheets. Out of the list, the Change() event is probably the one that most oftenhas code associated with it. A Change() occurs when a user alters the contents(value) of one or more cells on the sheet. Worksheet formula recalculations don’ttrigger this event, but they do trigger the Calculate() event. Ameetz.com
  8. 8. The ‘Target’ and ‘Cancel’ ObjectsOften in worksheet event stubs provided by the VBE you will see reference to twospecial objects (sometimes more or others also): Cancel and/or Target. Targetrepresents the Range [which is an object that represents a single cell, a group ofcells, one or more rows and/or one or more columns] that is active at the time theevent took place. Think of Target as the actual object itself. Anything you do toTarget is done to the actual Range that it represents. Changes made to Target willappear on the sheet itself.The Cancel object is a Boolean type object. A Boolean object can only have oneof two conditions assigned to it: TRUE or FALSE. By default a Boolean object isFALSE (and has a numeric value of zero). If your code sets Cancel = TRUE thenthe underlying event action is cancelled: the DoubleClick never takes place or theRightClick never gets completed. These are handy events to use to take veryspecial actions with – you can have someone double-click in a cell (and setCancel = True) to begin a series of events unique to that cell. A real world exampleof this type of thing in one application I developed is that in a data area matrix thathas dates in the top row, a double-click on a date causes all rows with an emptycell in that column to become hidden: a kind of auto filter based on empty cells forthat one column. Ameetz.com
  9. 9. Procedures: Function and SubCode modules contain code, and that code is placed into procedures, andprocedures fall into two categories: Sub (or subroutines) and Function(s).FUNCTIONSThe difference between a Sub and a Function is simply that a function can returna value to the procedure that called it. That procedure can be anotherFunction, a Sub or even to a worksheet cell. When it is done using a worksheetformula, the Function is known as a User Defined Function, or UDF. Potentiallyall Functions are UDFs.One other distinction between Functions and Subs is that (generally) Functionscan only affect a single cell in a workbook, while Subs can do their work andaffect almost any aspect of a workbook or worksheet. When it is used as aUDF, it can only affect the cell that it is called from; it cannot alter the contents ofother cells. Ameetz.com
  10. 10. SUBSSub procedures are just like Functions, except that they do not return avalue in the same way that a Function does. They can acceptarguments, or not, just like a Function does. VBA Sub Procedure Example Ameetz.com
  11. 11. VBA Function Procedure ExampleThe word Macro is slang for the word VBA procedure.• A procedure is defined as a named group of statements that are run as a unit. A statement is simply 1 complete line of code.• VBA procedures are used to perform tasks such as controlling Excel’s environment, communicating with databases, calculating equations, analyzing data etc. Ameetz.com
  12. 12. What is a VBA Procedure? Contd..• A VBA procedure unit or block consists of a procedure statement (Sub or Function) and an ending statement with statements in between.• A VBA procedure are constructed from three types of statements: executable, declaration and assignment statements. The statements between a procedure’s declaration and ending statement (i.e. Sub and End Sub) perform the procedures task; what you are trying do. •For example, the procedure to the right commands Excels Sort feature on the active worksheet when it is run.• Procedures are typed and stored in a Module.• Procedures are executed or run (same meaning) in order to apply their statements. When a procedure is run, its statements (i.e. lines) are executed in a top-down line by line fashion performing operations. Think of reading a book page. Note that typing a procedure in a module does not run it. You must do this after typing it by variety of different methods. Until you run it, it is just basically text sitting in a document.• VBA has two types of procedures: Sub procedures and Function procedures. Ameetz.com
  13. 13. Sub ProceduresSub procedures are written when you want to command Excel like creating achart, analyzing data, coloring cells, copying and pasting data.Function ProceduresFunction procedures are created when you want to make your own customworksheet functions or perform a calculation that will be used over and overagain. Note that Sub procedures can also do calculations.What to WriteSo if you want to do a task in Excel, you write a Sub procedure, if you want towrite a custom worksheet function, you write a Function procedure. Are theirgrey areas between the two, yes, but do not worry about them when first startingout Ameetz.com
  14. 14. In this example, you create an Excel macrothat converts selected formulas to theircurrent values. Sure, you can do thiswithout a macro, but it’s a multistepprocedure.To convert a range of formulas to values,you normally complete the following steps:1. Select the range that contains theformulas to be converted.2. Copy the range to the Clipboard.3. Choose Edit Paste Special.4. Click the Values option button in thePaste Special dialog box, whichis shown in Figure 2-1.5. Click OK.6. Press Esc.This clears the cut-copy mode indicator (themoving border) in the worksheet. Ameetz.com
  15. 15. Here comes the hands-on part. Follow these instructions carefully:1. Select the range of cells that contains your formulas.The selection can include both values and formulas. In my case, I chosethe range A1:D10.2. Choose Tools Macro Record New Macro.The Record Macro dialog box appears, as shown in Figure 2-3.3. Enter a name for the macro.Excel provides a default name, but it’s better to use a more descriptive name.ConvertFormulas is a good name for this one. 1 No Spaces Ameetz.com

×