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.
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)
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
Pivot Table ExamplePivot Table on the above sample data will look like Field List
Pivot Chart ExamplePivot Chart on the above sample data will look like
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
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
First Step to VBA : MacrosAssign Macro to An Event
• Demonstration example• A macro to get a text file to excel
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
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.
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 ….
Object Based Programming Language C++, Java, etc. are OOP (Object Oriented Programming) Language VBA is an Object Based Programming Language What is Object?
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”.
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”
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)
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
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.
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
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
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
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”)
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
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
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
Cells property With range objects Range(“A1:B10”).Cells(4) = 400 Will change the value of B2 Worksheets(“Sheet1”).Cells.ClearContents
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
Example to modify the previously created macro & change thepath of the text file or pick the file path from a cell inworkbook
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 =
VariablesVariable is a named storage location in the computer’smemoryCan accommodate wide variety of data types
Data typesInteger, Long, Single, Double, CurrencyDateStringObjectOthers…
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”
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
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
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
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
Case Is… Syntax
Use a Do Until…Loop Sub DoUntilLoop () Do Until ActiveCell = “” Code is written here Loop End Sub
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
More MethodsPrintPreview Worksheets(2).PrintPreviewPrintOut Worksheets(2).Printout Worksheets(“SE Sales”).PrintOut
VBA - Functions Function Public , Private, Return Value Parameter
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
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
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
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
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
• Create a code to import data from multiple csv files
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.
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.
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.