EXCEL VBA 101 Current Status Waiting Using Excel/VBA to Speed-up Daily Data Processing An Introduction to VBA Yongjun Chen Click Me to Start …

Slides:



Advertisements
Similar presentations
1B40: Data analysis 1 Objects Visual Basic is an (OO) object-oriented language. Performing a task in Visual Basic (VB) or.
Advertisements

1 Overview Introduction to VBA The Visual Basic Editor (VBE) –First Program Getting Started with VBA –Subroutines –Declaring variables –Input boxes and.
Using VB with MS Applications R. Juhl, Delta College.
ISOM3230 Business Applications Programming
Excel and Visual Basic. Outline Data exchange between Excel and Visual Basic. Programming VB in Excel.
Object Oriented Programming A programming concept which views programs as objects with properties and ways to manipulate the object and the properties.
Modeling using VBA. Covered materials -Userforms -Controls -Module -Procedures & Functions -Variables -Scope.
Essence of programming  Branching  Repetitions.
Visual Basic for Applications. What it does Extends the features and built in functions of Excel – Create and run VB procedures – Some may be easy to.
Office 2003 Post-Advanced Concepts and Techniques M i c r o s o f t Excel Project 7 Using Macros and Visual Basic for Applications (VBA) with Excel.
Exploring Microsoft Excel 2002 Chapter 9 Chapter 9 A Professional Application: VBA and Date Functions By Robert T. Grauer Maryann Barber Exploring Microsoft.
Using Macros and Visual Basic for Applications (VBA) with Excel
Developing an Excel Application
Tutorial 8: Developing an Excel Application
XP New Perspectives on Microsoft Excel 2003, Second Edition- Tutorial 8 1 Microsoft Office Excel 2003 Tutorial 8 – Developing an Excel Application.
AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
String Variables Visual Basic for Applications 4.
Microsoft Excel 2003 Illustrated Complete with Excel Programming.
Exploring Office Grauer and Barber 1 Creating More Powerful Applications: Introduction to VBA(Wk9)
Using the Visual Basic Editor Visual Basic for Applications 1.
Macros Tutorial Week 20. Objectives By the end of this tutorial you should understand how to: Create macros Assign macros to events Associate macros with.
Adding Automated Functionality to Office Applications.
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
COMPREHENSIVE Excel Tutorial 8 Developing an Excel Application.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
Project 9 Using Visual Basic for Applications (VBA) to Customize and Automate Excel Jason C. H. Chen, Ph.D. Professor of Management Information Systems.
Microsoft Excel 2007 © Wiley Publishing All Rights Reserved. The L Line The Express Line to Learning L Line.
VBA (Visual Basic for Applications) What is Excel, just a spreadsheet? Time for Demos...
© McGraw-Hill Companies, Inc., McGraw-Hill/Irwin Extended Learning Module M Programming in Excel with VBA.
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
Automating Tasks with Visual Basic. Introduction  When can’t find a readymade macro action that does the job you want, you can use Visual Basic code.
Enhancing User Interaction Through Programming
Creating Macros Using VBA. Assigning a Macro to a Button Display the Forms toolbar. Click the Button icon. Click and drag the mouse pointer to specify.
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Chapter 11: Introduction to the Visual Basic Environment Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University.
Week 8.  Recap  User Forms  Input Validation Message Boxes Input Boxes  Conversion Functions.
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA 1 Lecture Outline Record macro and examine VBA code VBA Editor (IDE)
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Automating Database Processing Chapter 6. Chapter Introduction Design and implement user-friendly menu – Called navigation form Macros – Automate repetitive.
Visual Basic for Applications Macro Programming For Microsoft Office.
VBA Lab 2 I ns.Samia Al-blwi. Visual Basic Grammar Object: Visual Basic is an object-oriented language. This means that all the items in Excel are thought.
OCC Network Drives  H:\  P:\ 
Using Visual Basic for Applications in Microsoft Project Sean Vogel.
Chapter 9 Macros And Visual Basic For Applications.
1 MIS309 Database Systems Introduction to Microsoft Access.
INSERT BOOK COVER 1Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall. Exploring Getting Started with VBA for Microsoft Office 2010 by.
Chapter 11: Introduction to VBA Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
A lesson approach © 2011 The McGraw-Hill Companies, Inc. All rights reserved. Microsoft® Excel 2013.
Visual Basic Objects / Properties / Methods PropertyAdjective ObjectNoun Part of the application Attribute MethodVerb Action to do something.
1 Visual Basic for Applications - VBA IE What is VBA?  VBA comes with Office u Objects (e.g. of Excel) are exposed for use by VBA u Visual Basic.
Macros in Excel Using VBA Time Required – 5 hours.
Chapter 10 Using Macros, Controls and Visual Basic for Applications (VBA) with Excel Microsoft Excel 2013.
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
The Advantage Series ©2005 The McGraw-Hill Companies, Inc. All rights reserved Chapter 12 Introducing Visual Basic for Applications Microsoft Office Excel.
Excel Tutorial 8 Developing an Excel Application
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
VBA (Visual Basic for Applications) What is Excel, just a spreadsheet?
Microsoft Office Illustrated
Excel VBA Day 3 of 3 Tom Vorves.
Learning Excel Session 9 and 10 Dr. Chaitali Basu Mukherji.
Exploring Microsoft Excel
Using Excel/VBA to Speed-up Daily Data Processing
Presentation transcript:

EXCEL VBA 101 Current Status Waiting Using Excel/VBA to Speed-up Daily Data Processing An Introduction to VBA Yongjun Chen Click Me to Start …

What is VBA What is Object How to Record Macro VBA Editor Window Example 1 VBA Fundamental Create User Defined Functions (Example 2) Work with Workbook & Worksheet I/O with External Data Files (Example 3) Capture Built-in Event (Example 4) An Introduction to VBA - Agenda

An Introduction to VBA - What is VBA  An abbreviation for Visual Basic for Applications  Official name is "Visual Basic, Applications Edition."  VBA is Microsoft's 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.

An Introduction to VBA - 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 ….

An Introduction to VBA - VBA- Object Based Programming Language  C++, Java, etc. are OOP (Object Oriented Programming) Language  VBA is an Object Based Programming Language  What is Object?

An Introduction to VBA - VBA Object Based Programming Language  Concepts – 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”.

An Introduction to VBA - VBA Object Based Programming Language  Concepts – 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”

An Introduction to VBA - VBA Object Based Programming Language  Concepts – 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)

An Introduction to VBA - VBA Object Based Programming Language  Concepts – 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

An Introduction to VBA - VBA Object Based Programming Language  Concepts – 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.

An Introduction to VBA - VBA Object Based Programming Language  Concepts – 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

An Introduction to VBA - VBA Object Based Programming Language  Concept Summary

An Introduction to VBA - VBA Object Based Programming Language  Understand Object Concepts Workbooks("book1.xls").Worksheets("sheet1").Range("A1").Font.Bold = True ActiveWorkbook.ActiveSheet.Cells(1, 1).ClearContents Private Sub Workbook_Open() MsgBox "Thank you for choosing VBA" End Sub

An Introduction to VBA - VBA Object Based Programming Language  Quiz 1 Which of the following is not a valid Excel object  i) ActiveWorkbook  ii) ActiveSheet  iii) ActiveCell  iv) ActiveRange A) NoneB) iC) iiiD) iv

An Introduction to VBA - First Step to VBA : Macros  Record 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

An Introduction to VBA - First Step to VBA : Macros  Assign 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

An Introduction to VBA - First Step to VBA : Macros  Assign Macro to An Event

An Introduction to VBA - Second Step to VBA : Edit Macro  VBA 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 Tools>Options>Docking Window

An Introduction to VBA - Second Step to VBA : Edit Macro  VBA 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

An Introduction to VBA - Second Step to VBA : Edit Macro  Sample Record Macro Understand Macro Modify Macro Assign Macro to Button Click Event See Demo

An Introduction to VBA - Second Step to VBA : Edit Macro  Understand VBA Editor Window Project window Shows files, sheets and modules Property window Show properties of active object and let user to modify the properties Code window VBA codes are here. Auto list member Auto list data / parameter

An Introduction to VBA - Second Step to VBA : Edit Macro  Quiz 2 For the following four actions  i) Type formula in another workbook/file  ii) Change macro security level  iii) Print another worksheet in the same workbook  iv) Open a Word file What can not be recorded in a macro A) ii onlyB) iv onlyC) ii & ivD) iii & iv

An Introduction to VBA - Third Step to VBA : Write VBA Code  Fundamental of VBA  Variables: can be define explicit or implicit use dim statement  Constant use const pi =  Function: pair of function … end function  Subroutine: pair of sub … end sub  Comment use single quotation ‘  Continuation use underline _  Use with … end with for object  Assign object use set and assign data variable use =

An Introduction to VBA - Third Step to VBA : Write VBA Code  Fundamental of VBA  Decision Making use If… elseif…else…end if  Multiple Selection/Decision Making Select Case Var… Case A … Case B…Case Else… End Select  Loop use Do While … LoopDo … Loop Until For … NextFor Each … Next  Array – dim Data(10) as integer, Val(2 to 8) as object

An Introduction to VBA - Third Step to VBA : Write VBA Code  Fundamental of VBA  Function  Public, Private, Return Value  Parameter  Subroutine  Public, Private, No Return Value  Parameter

An Introduction to VBA - Third Step to VBA : Write VBA Code  Understand Code Worksheets("sheet1").Activate Range("A1:A10").ClearContents For i = 1 To 10 Range("A" & i) = i ^ 2 Next Range("A1:A10").Font.Bold = True For Each cl In Range("A1:A10") If cl.Value 75 Then cl.Font.Italic = True Else cl.Font.Underline = True End If Next Msgbox “All done” 1)Make sheet1 active 2)Clear range A1:A10 3)Type 1,4,9,…100 in to range A1, A2, … A10 4)Set font to bold for all cells in the range 5)Make cell italic if the cell’s value is 75, otherwise underline 6)Display message “All done”

An Introduction to VBA - Third Step to VBA : Write VBA Code  Quiz 3 Function myTest(a as integer, b as integer) as integer  myTest = a + b  myTest = myTest + 1  Range("D1").Value = myTest  MsgBox "All done” End function Which statement will cause problem for myTest A) 1 st oneB) 2 nd one C) 3 rd one D) 4 th one

An Introduction to VBA - Third Step to VBA : Write VBA Code  Create User-Defined Functions Public Function myFun(x As Integer, y As Integer) As Integer myFun = x * y + x / y End Function Must start with Keyword “Function” and end with “End Function” Arguments Return Value Type The return value must be assigned to the function name See Demo

An Introduction to VBA - Third Step to VBA : Write VBA Code  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".Subject = "Results for Analysis".SaveAs Filename:="Results.xls" End With Use With Statement (faster)

An Introduction to VBA - Third Step to VBA : Write VBA Code ' Open / Activate / Save /Close Workbook Fname ="C:\AnalysisResutls\Results.xls" Workbooks.Open(Fname) Workbooks("Results.xls").Activate Workbooks("Results.xls").Save Workbooks("Results.xls").Close SaveChanges:=True ‘ ' Loop All Open Workbooks Dim wkbk As Workbook For Each wkbk In Workbooks Msgbox "Workbook " & wkbk.Name & " Has " & Workbooks(k).Sheets.Count & " Sheets", vbInformation Next For Each Statement

An Introduction to VBA - Third Step to VBA : Write VBA Code  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

An Introduction to VBA - Third Step to VBA : Write VBA Code ‘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

An Introduction to VBA - Third Step to VBA : Write VBA Code Sub Output00() Open ThisWorkbook.Path & "\test.dat" For Output As #1 Print #1, "This is a test of using VBA to output results" Print #1, "The result is " & Worksheets(“Summary").Range(“A1").Value Print #1, "End of Test File" Close #1 End Sub  I/O with External Data Files

An Introduction to VBA - Third Step to VBA : Write VBA Code Sub Input00() Dim tmpstr As String Open ThisWorkbook.Path & "\test.dat" For Input As #1 Line Input #1, tmpstr Range(“A1").Value = tmpstr Close #1 End Sub  I/O with External Data Files See Demo

An Introduction to VBA - Third Step to VBA : Write VBA Code Private Sub Workbook_BeforeSave (ByVal SaveAsUI As Boolean, Cancel As Boolean) MsgBox “ …” End Sub Private Sub Worksheet_SelectionChange(ByVal Target As Range) Msgbox “ …” End Sub  Capture Built-In Event See Demo

An Introduction to VBA - Third Step to VBA : Write VBA Code Sub MySummarize() ' ' Modified from Summarize Macro ' '1) Define variables - worksheet and file id Dim sht As Worksheet, wkbk As Workbook Dim ifile As Integer, sfile As String '2) Assign variable: object use set and data use = Set sht = Sheets.Add  Review/Understand of Our First Macro

An Introduction to VBA - Third Step to VBA : Write VBA Code With sht ' use with to speed up and save typing.Name = "Summary2".Range("A1").Value = "Case Name".Range("A2") = "Case ID" ' default property is value.Range("A3") = "Weight".Range("A4") = "XCG".Range("A5") = "YCG".Range("A6") = "ZCG".Range("A1:A6").Font.Bold = True.Range("A1:A6").HorizontalAlignment = xlLeft  Review/Understand of Our First Macro

An Introduction to VBA - Third Step to VBA : Write VBA Code For ifile = 1 To 3 Step 1 ' loop all files sfile = "Case" & ifile & ".xls" ' create file name sfile = ThisWorkbook.Path & "\" & sfile ' specify file path Set wkbk = Workbooks.Open(sfile) ' open file wkbk.ActiveSheet.Range("B1:B6").Copy ' copy data.Paste.Cells(1, ifile + 1) ' paste to this workbook wkbk.Close SaveChanges:=False ' close file Next.Columns("A:D").AutoFit End With MsgBox "File Summarize are Done", vbInformation, "VBA Demo"  Review/Understand of Our First Macro

An Introduction to VBA - Learning via Practice & Ask Questions / Comments Where to get help: Use F1 key in VBA editor (like type keyword msgbox to search help) Microsoft Users Excel Programming Discussion us/default.mspx?dg=microsoft.public.excel.programming&lang=en&cr=US