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.

Vba

2,270 views

Published on

Published in: Technology

Vba

  1. 1. An Introduction to VBA
  2. 2. Excel FunctionsThe VLookup function searches for value in the left-most column oftable_array and returns the value in the same row based on theindex_number.Syntax:VLookup( value, table_array, index_number, not_exact_match ) value is the value to search for in the first column of the table_array. table_array is two or more columns of data that is sorted in ascending order. index_number is the column number in table_array from which the matching value must be returned. The first column is 1. not_exact_match boolean value to determine if you are looking for an exact match based on value.
  3. 3. Example for VlookupSample Data: A range named as Master Empid Name Basic e003 ashok 2340 e002 nirvay 5670 e003 bajrangi 3450 e004 jeet 5670 e005 shubneet 1234 e006 gulab 5432Now to obtain the Basic of employees in other sheet use Vlookup asfollows:=VLOOKUP(A4,master,3,FALSE)
  4. 4. Pivot Table & Pivot ChartUse a PivotTable report to summarize, analyze, explore, andpresent summary data. Use a PivotChart report to visualize thatsummary data in a PivotTable report, and to easily seecomparisons, patterns, and trends.Both a PivotTable report and a PivotChart report enable you tomake informed decisions about critical data in your enterprise
  5. 5. Pivot Table & Pivot Chart ExamplesSample Data Year Zone Qtr Sales 2008west 1 34 2009west 1 56 2010west 1 43 2008west 2 7 2009west 2 6 2010west 2 5 2008west 3 4 2009west 3 12 2010west 3 0 2008west 4 9 2009west 4 8 2010west 4 7 2008east 1 6 2009east 1 5 2010east 1 4
  6. 6. Pivot Table ExamplePivot Table on the above sample data will look like Field List
  7. 7. Pivot Chart ExamplePivot Chart on the above sample data will look like
  8. 8. VBA
  9. 9. First Step to VBA : MacrosRecord Macro • Similar to audio/video recorder • Record all the steps you conduct and write them in VBA code If macros are disabled when you start Excel, change the security level to medium
  10. 10. First Step to VBA : MacrosAssign Macro to An Event • Normally User Run Macros from VBA Edit Window – Unnecessary • User Can Assign Macro to An Event, Normally a Button Click Event • Easy to Execute and Easy to Remember • Give a Good Name for The Button and Click the Button to Run the Macro
  11. 11. First Step to VBA : MacrosAssign Macro to An Event
  12. 12. • Demonstration example• A macro to get a text file to excel
  13. 13. Second Step to VBA : Edit MacroVBA Editor Window • Press Alt+F11 to Activate VBA Window • Or Go to Menu Tools>Macros>Visual Basic Editor • Project Explore Window • Properties Window • Code Window
  14. 14. What is VBA• An abbreviation for Visual Basic for Applications• Official name is "Visual Basic, Applications Edition."• VBA is Microsofts common application programming (macro) language for Word, Excel, Access, etc.• Also being implemented in other Microsoft applications such as Visio and is at least partially implemented in some other applications such as AutoCAD...• VBA and VB have a lot in common, but they are different. VB is a programming language that lets you create standalone executable programs.
  15. 15. What Can You Do With VBA• Write Macros to Automate Labor-Intensive and Repetitive Tasks• Create User-Defined Functions to Achieve Complicated Functionality• Create Standard Windows Menu/Tool Bars for Interface• Interact with Other Windows Programs (like Matlab)• I/O with External Files• Database Operation ….
  16. 16. Object Based Programming Language C++, Java, etc. are OOP (Object Oriented Programming) Language VBA is an Object Based Programming Language What is Object?
  17. 17. Object Based Programming LanguageConcepts – Containers or Collections  A Group of Similar Objects Share Common Properties, Methods and Events  Such as Workbooks, Worksheets, etc.  Worksheets is a collection of all the Worksheet objects in the specified or active workbook.  Worksheets(1) refers to the 1st worksheet of current active workbook.  Worksheets (“mooring”) refers to the worksheet named “mooring”.
  18. 18. Object Based Programming LanguageConcepts – Objects • Such as Worksheet, Workbook, Range, Cell, Chart, Name, etc. • Worksheets(1) is an Object Referring to the First Sheet • Range("A1:B15") is an Object Referring to a Range • Cells(1,1) or Range(“A1”) is an Object Referring to Range “A1”
  19. 19. Object Based Programming LanguageConcepts – Properties • Properties are the Physical Characteristics of Objects and Can be Measured or Quantified. • Properties for Collections - Worksheets.Count (Read Only) - Worksheets.Visible = True (Read and Write) • Properties for Object - Range("A1:B15").Rows.Count (Read Only) - Range("A1:B15").Font.Bold = True (Read and Write)
  20. 20. Object Based Programming LanguageConcepts – Methods • Methods are the Actions that Can be Performed by Objects or on Objects • Methods for Collections - Worksheets.Add - Worksheets.Delete • Methods for Objects - Range("A1:B15").ClearContents - ActiveCell.Copy
  21. 21. Object Based Programming LanguageConcepts – Events • Objects Can Respond to Events, Such as Mouse Click, Double Click on a Cell, Active a Worksheet, Open/Close/Save a Workbook, etc. • Worksheet Events – Such as Activate, Deactivate, Change, Selection Change, Before Double Click, etc. • Workbook Events- Such as Activate, Deactivate, Open, Before Close, Before Saving, Before Print, New Sheet.
  22. 22. Object Based Programming LanguageConcepts – Referring To • Use brackets () to refer to member object Worksheets(“mooring”) • Use dot . to refer to child object or object‟s properties and methods Worksheets(“mooring”).Range(“A1:B3”).Font.Bold
  23. 23. Second Step to VBA : Edit MacroVBA Editor Window • Use Tools/Options to Enable Auto Syntax Check, Auto List Members, etc. • Use Tools/Properties to Protect Your Code with Password – You Must Remember the Password • Insert Module, Procedure, Form
  24. 24. Second Step to VBA : Edit MacroUnderstand VBA Editor Window Project window Shows files, sheets and Auto list member modules Auto list data / parameter Property window Code window Show properties of VBA codes are here. active object and let user to modify the properties
  25. 25. Working with objects using VBAObjects can be manipulated using the collections they belongto, specifying their location in the object hierarchy using thedot notation.  Worksheets(“Sheet1”)  Worksheets(1)  Workbooks(“Book1”).Worksheets(“Sheet1”)  Worksheets(“Sheet1”).Range(“A1”)  Application.Workbooks(“Book1”)._ Worksheets(“Sheet1”).Range(“A1”)
  26. 26. Accessing properties and methods Properties  Reading  Worksheets(“Sheet1”).Range(“A1”).Value  Setting  Range(“A1”).Value=123 Methods  Range(“A1:D5”).Clear
  27. 27. Referring to range objects  Using the Range property  Applies to:  Application object  Worksheet object  Range object  Cells property of a Worksheet object  Offset property of a Range object
  28. 28. Range propertyObject.Range(cell1)Object.Range(cell1, cell2)Worksheets(“Sheet1”).Range(“A1”). Value = 1Range(“Input”).Value = 5Range(“A1:B10”).Value=3Range(“A1”, “B10”)=3Range(“C1:C10 “,”A6:E6”)=5Range(“A1, A5, B4, F5”)=6
  29. 29. Cells property  Worksheets(“Sheet1”).Cells(1,1)=5  Changes the value of A1  Cells(5,2) = 4  Changes the value of B5  Cells(257) = 6  Changes cell A2
  30. 30. Cells property With range objects  Range(“A1:B10”).Cells(4) = 400  Will change the value of B2 Worksheets(“Sheet1”).Cells.ClearContents
  31. 31. Offset property Applies only to the Range object Range(“B1”).Offset(1,0).Value=4  Changes B2 value to 4 Range(“C6”).Offset(-4,-2).Value = 5  Changes A2 value to 5
  32. 32. Example to modify the previously created macro & change thepath of the text file or pick the file path from a cell inworkbook
  33. 33. Third Step to VBA : Edit MacroFundamental of VBA • Variables: can be define explicit or implicit use dim statement • Constant use const pi =3.1415926 • Control Statements • Function: pair of function … end function • Comment use single quotation „ • Continuation use underline _ • Use with … end with for object • Assign object use set and assign data variable use =
  34. 34. VariablesVariable is a named storage location in the computer’smemoryCan accommodate wide variety of data types
  35. 35. Data typesInteger, Long, Single, Double, CurrencyDateStringObjectOthers…
  36. 36. VariablesIt is better to determine the data type of a variable. Yourapplications will be executing much faster!Use Option Explicit to force yourself to declare the variablesyou useConstant is a “variable” that retains its value Dim Const companyName as String = “City University”
  37. 37. Variable’s lifetime and scopeTwo important concepts associated with variables:  Scope  Defines which procedures can use that variable  Lifetime  Defines how long that variable retains the values assigned to it
  38. 38. Variable lifetimeThe lifetime of the variable depends where it is declared  In a procedure  The lifetime is limited to the time taken to run the procedure  In a procedure using the Static keyword  The lifetime is extended to the time that the workbook is open  In the declarations section  The lifetime is extended to the time that the workbook is open
  39. 39. Variable scopeThe scope of the variable depends where it is declared:  In a procedure  It is visible only within the procedure code  In a module  It is visible only within the module code  In a module as Public  It is visible from all open workbooks  In a module as Private  It is visible only within the module code
  40. 40. Control Statements in VBADecision Making use If… elseif…else…end ifMultiple Selection/Decision Making Select Case Var… Case A … Case B…Case Else… End SelectLoop use Do While … Loop Do … Loop Until For … Next For Each … Next
  41. 41. If…Then Syntax
  42. 42. If…Then…Else Syntax
  43. 43. Case Is… Syntax
  44. 44. Use a Do Until…Loop Sub DoUntilLoop () Do Until ActiveCell = “” Code is written here Loop End Sub
  45. 45. For Next Sub ForNext Loop () For Counter = 1 to 10 [Step 1] Code is written here Next Counter – continues to collect iterations as a count End Sub
  46. 46. Input - Output Dialog box Input box Message box Command buttons
  47. 47. Dialog box and User Input
  48. 48.  A simple example of accepting two strings and concatenating them.
  49. 49. Working with Worksheets Insert, Copy and Delete Worksheets Rename worksheets Change worksheet order Print worksheets
  50. 50. More Methods Add Method Worksheets.Add Delete Method Worksheets(2).Delete Copy Method Worksheets(2).Copy After:=Worksheets(2) Rename Worksheet(“Sheet3”).Name = “Mysheet”
  51. 51. More MethodsPrintPreview  Worksheets(2).PrintPreviewPrintOut  Worksheets(2).Printout  Worksheets(“SE Sales”).PrintOut
  52. 52. VBA - Functions Function Public , Private, Return Value Parameter
  53. 53. Create User-Defined Functions Public Function myFun(x As Integer, y As Integer) As Integer myFun = x * y + x / y End Function Arguments Return Value Type Must start with Keyword “Function” and end with “End The return value must be Function” assigned to the function name
  54. 54. VBA Examples
  55. 55. Work with Workbook Refer A Workbook Workbooks(1) Use Index Workbooks("Results.Xls") Use Name ActiveWorkbook Refers to the Active Workbook Create A New Workbook Dim NewWkBk as Workbook Set NewWkBk = Workbooks.Add With NewWkBk .Title = "Analysis Resultd"Use WithStatement .Subject = "Results for Analysis" .SaveAs Filename:="Results.xls"(faster) End With
  56. 56. Work with Workbook Open / Activate / Save /Close WorkbookFname ="C:AnalysisResutlsResults.xls"Workbooks.Open(Fname)Workbooks("Results.xls").ActivateWorkbooks("Results.xls").SaveWorkbooks("Results.xls").Close SaveChanges:=True „ For Each Loop All Open Workbooks StatementDim wkbk As WorkbookFor Each wkbk In Workbooks Msgbox "Workbook " & wkbk.Name & " Has " & Workbooks(k).Sheets.Count & " Sheets", vbInformationNext
  57. 57. Work with Worksheet Refer A Worksheet Worksheets(1) Use Index Worksheets("Sheet1") Use Name ActiveWorksheet Active Worksheet Workbooks("TestSht.xls").Worksheets("Sht2") Add /Activate/Delete A New Worksheet Workbooks("TestSht.xls").Worksheets.Add Sheets("NewSht").Activate Workbooks(“A.xls").Sheets(“B").Activate Sheets("NewSht").Delete
  58. 58. Work with Worksheet „Rename / Extract A Worksheet Workbooks("TestSht.xls").Sheets("NewSht").name = "NewSht2" MsgBox "Current Sheet Name is " & ActiveSheet.Name Count Sheets MsgBox "Current Workbook Has " & Sheets.Count & " sheets" Loop All Sheets Dim sht As Worksheet For Each sht In ActiveWorkbook.Sheets MsgBox sht.Name & " A1 = " & Range(“A1").Value Next
  59. 59. • Create a code to import data from multiple csv files
  60. 60. Debugging a macroWhen you write a macro, you need to test it and correct anyerrors in the macro.To debug a macro insert breakpoints. Breakpoint enables youto step through the macro, one command at a time. As youstep through the macro, you can correct any errors youlocate.
  61. 61. Other Methods for debugging VBA code Immediate Window The Immediate Window is a window in the VBE in which you can enter commands and view and change the contents of variables while you code is in Break mode or when no macro code is executing. Debug.Print You can use the Debug.Print statement anywhere in your code to display messages or variable values in the Immediate Window. Debug.Assert In Excel 2000 and later, you can use Debug.Assert statements to cause the code to break if a condition is not met. Locals Window The Locals Window displays all the variables in a procedure (as well as global variables declared at the project or module level) and their values.
  62. 62. Debugging a vba code example 1. Write an excel code to take input from a cell and export the current sheet into that data, use local window, immediate window, and debug.print to check that the code is working correctly.
  63. 63. Live Example
  64. 64. Referenceshttp://www.vbtutor.net/VBA/vba_tutorial.htmlFor Demo Examples:http://www.ozgrid.com/VBA/

×