vba_lecture1

34
VBA (Visual Basic for Application) Let’s Get Started…

Upload: anhphuong

Post on 30-Jan-2016

14 views

Category:

Documents


0 download

DESCRIPTION

VBA

TRANSCRIPT

Page 1: VBA_Lecture1

VBA (Visual Basic for Application)Let’s Get Started…

Page 2: VBA_Lecture1

Introduction

What is the VBA?

• VBA stands for Visual Basic for Application.

• VBA is a programming language, also a macro language.

• VBA cannot create standalone applications and it exists within a host application such as Excel.

What is the Macro?

• Macro comes from the Greek - makros, which means large.

• Macro is something written in VBA and executed in Excel - Macro is VBA procedure.

Page 3: VBA_Lecture1

What VBA can do

Some interesting things VBA can do:

• Automating a recurring and repetitive task.

• Creating your own worksheet functions.

• Simplifying the workbook’s look and feel for other users

Page 4: VBA_Lecture1

Preparation

Getting Excel to display Developer tab

1. Right click any part of the Ribbon, choose Customize the Ribbon.

2. In the Customize Ribbon tab of the Excel Options dialog box, locate Developerin the second column.

3. Put a check mark next to Developer.

4. Click OK.

Page 5: VBA_Lecture1

Create the first macro

Description of first macro:

1. Type your name into a cell.

2. Enter the current date and time into the cell below.

3. Format both cells to display bold.

4. Change the font size of both cells to 16 point.

Page 6: VBA_Lecture1

Create the first macro

Preparation for Recording the macro:

1. Select a cell.

2. Choose Developer ➪ Code ➪ Record Macro.

3. Enter a name for the macro.

4. Click in the Shortcut Key box and enter Shift + N (for an uppercase N) as the shortcut key.

5. Make sure the Store Macro In setting is This Workbook.

6. Click OK.

The Record Macro dialog box closes, and Excel’s macro recorder is turned on. From this point, Excel monitors everything you do and converts it to VBA code.

Page 7: VBA_Lecture1

Create the first macro

Recording the macro:

1. Type your name in the active cell.

2. Move the cell pointer to the cell below and enter this formula: =NOW()

3. Select the formula cell and press Ctrl + C to copy that cell to the Clipboard.

4. Choose Home ➪ Clipboard ➪ Paste ➪ Values (V).

5. With the date cell selected, press Shift + up arrow to select that cell and the one above it (which contains your name).

6. Use the controls in the Home ➪ Font group to change the formatting to Bold and make the font size 16 point.

7. Choose Developer ➪ Code ➪ Stop Recording.

Page 8: VBA_Lecture1

Modify the macro

Modifying the macro:

1. Open Module 1.

2. Add and edit some code.

3. Run macro again for checking the change.

Page 9: VBA_Lecture1

Saving Workbooks

If you store one or more macros in a workbook, the file must be saved as a “macro-enabled” file type (*.XSLM)

Page 10: VBA_Lecture1

Environment for VBA

Open Visual Basic for Application:

1. Using Alt + F11.

2. Developer ➪ Code ➪ Visual Basic

Page 11: VBA_Lecture1

Visual Basic Editor (VBE)

We can understand the VBE likes bellow:

1. The VBE is a separate application where you write and edit your VBA macros.

2. Excel takes care of opening the VBE when you need it.

3. There is only one VBE window, and it works with all open Excel windows.

Page 12: VBA_Lecture1

Main components in VBE

VBE has some components which help you in coding macro:

1. Menu bar.

2. Toolbar.

3. Project window: displays a tree diagram that shows every workbook currently open in Excel.

4. Code window: A Code window is where you put your VBA code. Every object in a project has an associated Code window.

5. Immediate window

Page 13: VBA_Lecture1

VBA (Visual Basic for Application)Excel and Objects

Page 14: VBA_Lecture1

Objects and OOP

Software objects:

1. Similar to real-world objects.

2. They all have states (properties) and behaviors (method).

Object-Oriented Programming (OOP)

1. Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions" and data rather than logic.

2. They all have states (properties) and behaviors (method).

Page 15: VBA_Lecture1

Main concepts in OOP

OOP – Three important concepts:

1. Encapsulation means that a group of related properties, methods, and other members are treated as a single unit or object.

2. Inheritance describes the ability to create new classes based on an existing class.

3. Polymorphism means that you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.

Page 16: VBA_Lecture1

Objects in VBA

Application

Addin Window Workbook

Worksheet

Range

WorksheetFunction

Page 17: VBA_Lecture1

Collections in VBA

Wrapping Your Mind around Collections:

1. Collections are another key concept in VBA programming.

2. A collection is a group of objects of the same type.

3. A few examples of commonly used collections:

• Workbooks: A collection of all currently open Workbook objects.

• Worksheets: A collection of all Worksheet objects contained in a particular Workbook object.

• Charts: A collection of all Chart objects (chart sheets) contained in a particular Workbook object.

• Sheets: A collection of all sheets (regardless of their type) contained in a particular Workbook object.

Page 18: VBA_Lecture1

Collections in VBA

Wrapping Your Mind around Collections:

1. Collections are another key concept in VBA programming.

2. A collection is a group of objects of the same type.

3. A few examples of commonly used collections:

• Workbooks: A collection of all currently open Workbook objects.

• Worksheets: A collection of all Worksheet objects contained in a particular Workbook object.

• Charts: A collection of all Chart objects (chart sheets) contained in a particular Workbook object.

• Sheets: A collection of all sheets (regardless of their type) contained in a particular Workbook object.

Page 19: VBA_Lecture1

Referring to Objects

Referring to Objects is important:

1. We must identify the object that you want to work with.

2. You need to work with a specific object in a collection (such as a particular worksheet in a workbook).

• Worksheets(“Sheet1”) or Worksheets(1)

Page 20: VBA_Lecture1

Navigating through the hierarchy

Navigating:

1. If you want to work with the Application object, it’s easy: You start by typing Application.

2. You get to these objects by moving down the hierarchy and connecting each object on your way with the dot (.) operator.

• Examples:

To get to the Workbook object named Book1.xlsx, start with the Application object and navigate down to the Workbooks collection object: Application.Workbooks(“Book1.xlsx”)

To navigate farther to a specific worksheet, add a dot operator and access the Worksheets collection object: Application.Workbooks(“Book1.xlsx”).Worksheets(1)

You really want to get the value from cell A1 on the first Worksheet of the Workbook named Book1.xlsx: Application.Workbooks(“Book1.xlsx”).Worksheets(1).Range(“A1”).Value

Page 21: VBA_Lecture1

Simplifying object references

• If you were required to fully qualify every object reference you make, your code would get quite long, and it might be more difficult to read. Fortunately, Excel provides you with some shortcuts that can improve the readability.

• Example:

The Application object is always assumed. So you can change to:Workbooks(“Book1.xlsx”).Worksheets(1).Range(“A1”).Value

I If you’re sure that Book1.xlsx is the active workbook, you can omit that reference. And now Worksheets(1).Range(“A1”).Value

If you know the first worksheet is the currently active worksheet, then Excel will assume that reference and allow you to just type Range(“A1”).Value

Page 22: VBA_Lecture1

VBA (Visual Basic for Application)VBA Sub and Function Procedures

Page 23: VBA_Lecture1

Subs versus FunctionsThe VBA code that you write in the Visual Basic Editor is known as a procedure. The two most common types of procedures are Sub and Function.

Sub: A Sub procedure is a group of VBA statements that performs an action (or actions) with Excel. You need to work with a specific object in a collection (such as a particular worksheet in a workbook).

Sub ShowMessage()

MsgBox “Welcome to VBA class!”

End Sub

Function: A Function procedure is a group of VBA statements that performs a calculation and returns a single value (or an array).

Function CubeRoot(number)

CubeRoot = number ^ (1 / 3)

End Function

We can talk the procedure with return value is Function and the procedure without return value is Sub.

Page 24: VBA_Lecture1

Execute Sub procedureWe have many ways to run a Sub procedure:

1. Run ➪ Run Sub/UserForm command (in the VBE).

2. From Excel’s Macro dialog box.

3. Using the Ctrl + key (or Ctrl + Shift + key) shortcut assigned to the Sub procedure.

4. Clicking a button or a shape on a worksheet. The button or shape must have a Sub procedure assigned to it (Right-click the shape ➪ Assign Macro).

5. From another Sub procedure that you write (Call <name of Sub procedure>).

6. From the Immediate window in the VBE. Just type the name of the Sub procedure and press Enter.

Sub ShowCubeRoot()

Num = InputBox("Enter a positive number")

MsgBox Num ^ (1 / 3) & " is the cube root."

End Sub

Page 25: VBA_Lecture1

Execute Function procedure

We have two ways to run a Function procedure:

1. By calling the function from another Sub procedure or Function procedure.

2. By using the function in a worksheet formula.

Function CubeRoot(number)CubeRoot = number ^ (1/3)

End Function

Sub CallerSub()Ans = CubeRoot(125)MsgBox Ans

End Sub

Page 26: VBA_Lecture1

VBA (Visual Basic for Application)Macro

Page 27: VBA_Lecture1

Macro vs Video

Page 28: VBA_Lecture1

Preparing to record

Ultimately, the success of a recorded macro depends on five factors:

1. How the workbook is set up while you record the macro.

2. What is selected when you start recording.

3. Whether you use absolute or relative recording mode.

4. The accuracy of your recorded actions.

5. The context in which you play back the recorded macro.

Page 29: VBA_Lecture1

Relative or Absolute

Absolute:

1. Make sure that the Developer ➪ Code ➪ Use Relative References button is not highlighted and then choose Developer ➪ Code ➪ Record Macro.

2. Type Absolute as the name for this macro.

3. Click OK to begin recording.

4. Activate cell B1 and type Jan in that cell.

5. Move to cell C1 and type Feb.

6. Move to cell D1 and type Mar.

7. Click cell B1 to activate it again.

8. Stop the macro recorder.

9. Examine the Module1 module.

Page 30: VBA_Lecture1

Relative or Absolute

Relative:

1. Activate cell B1.

2. Choose Developer ➪ Code ➪ Record Macro.

3. Name this macro Relative.

4. Click OK to begin recording.

5. Click the Use Relative References button to change the recording mode to relative.

6. Type Jan in cell B1.

7. Move to cell C1 and type Feb.

8. Move to cell D1 and type Mar.

9. Stop the macro recorder.

Page 31: VBA_Lecture1

When using Record Macro

Using Record Macro:

1. When the aim is automation format.

Page 32: VBA_Lecture1

VBA (Visual Basic for Application)Essential VBA Language Elements

Page 33: VBA_Lecture1

Q & A

Page 34: VBA_Lecture1

Thank you