Top Banner
Week 2
37

Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Aug 05, 2018

Download

Documents

lydang
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Week 2

Page 2: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Macros revisited

The VBA Editor

The object model

Using variables

If statements

Page 3: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Record a macro that formats highlighted cells to appear as integers (enter some decimal numbers to test it on)

Create a Message Box that looks like this:

(tip the icon is called vbInformation)

Page 4: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Your macro might look something like this:

Sub Macro2()'' Macro2 Macro'

'Selection.NumberFormat = "0.00"Selection.NumberFormat = "0.0"Selection.NumberFormat = "0"

End Sub

Page 5: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Your macro should look something like this:

Sub IntegerFormat()

' Format highlighted cells as integer

Selection.NumberFormat = "0.00"Selection.NumberFormat = "0.0"Selection.NumberFormat = "0"

End Sub

Page 6: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Your macro should look something like this:

Sub IntegerFormat()

' Format highlighted cells as integer

With Selection.NumberFormat = “0“

End WithEnd Sub

Page 7: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Formatting Fonts

Record a new macro to format the

selected cells as follows:• Tahoma, Bold, Size 14

Edit your macro using With Selection.Font

ensuring that there is no unnecessary

code (don’t forget to End With)

Page 8: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

User friendly environment for writing VBA code

Access the VBE by pressing Alt-F11

The programming workspace includes:• The Code window

• The Project Explorer

Worksheets + Chart Sheets

ThisWorkbook

Modules (for VBA code)

User forms (for dialog boxes)

• The Properties Window

Page 9: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Project

explorer

Properties

window

Code

window

Immediate

window

Page 10: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

1. Provide sufficient comments • Start the line with a single quote

• The line is coloured green and ignored by VBA

2. Indent consistently • Provide a logical structure to your program

3. Use white space liberally Use Names wisely – “Macro1” is fine

now, but less helpful for future reference

10

Page 11: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Objects• Car, Engine, Spark plugs, Door(s)

Properties (Values)• Colour (red), Type (1.4l), Age (4 years), size (4-

door), Locked (True)

Methods (arguments)• Do Locking (central), Turn over, Spark, Drive

(10mph), Reverse

Events• Hit wall, Reach speed limit, Driver turns key

Page 12: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Examples of Objects:• Ranges, worksheets, charts, workbooks

Each object has properties, i.e. the attributes of the object• e.g., a cell has a Value property (either

text or number in the cell), a Formula property (the formula in the cell) and a HorizontalAlignment property (left, center or right).

Page 13: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Each object has methods, i.e. the things you can do to an object• e.g., a cell has the ClearContents method

to erase the content of the cell (equivalent to the delete key).

Some methods have arguments, i.e. qualifiers indicating how a method is performed • e.g., the Copy method has a Destination

argument.

Page 14: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Objects can be manipulated using the

collections they belong to, specifying their

location in the object hierarchy using the dot

notation.

• Worksheets(“Sheet1”)

• Worksheets(1)

• Workbooks(“Book1”).Worksheets(“Sheet1”)

• Worksheets(“Sheet1”).Range(“A1”)

• Application.Workbooks(“Book1”)._

Worksheets(“Sheet1”).Range(“A1”)

Page 15: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Online help tool.Click on the Object Browser button in the

Standard toolbar.Select Excel Libraries

• List of all objects (on the left)

• List of properties and methods for each object (on the right)

Properties: hand icon

Methods: green rectangular icon

To get help on any item, select it and click on the question mark button.

Page 16: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Variable:

A variable is a mechanism which enables

you to store information and use it while a

program is running. As the name implies,

it is possible to change the value during

the running of a program

Page 17: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Option explicit

Sub hello()Dim username As Stringusername = InputBox("Please enter your name")MsgBox "Hello " & username

End Sub

Page 18: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Valid variable names can contain text or

numbers but they must use a letter as the

first character.

You can't use a space, period (.),

exclamation mark (!), or the characters

@, /, &, $, # in the name.

Names cannot exceed 255 characters in

length (short and to the point is best)

Be descriptive

Page 19: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Byte

Integer

Long

Single

Double

Currency

Boolean

Date

String

Object

Variant

0 to 255

-32768 to 32767

-2.1 bn to 2.1 bl

Regular decimal numbers

Large decimal numbers

-9.22 trn to 9.22

True / False1/1/100 to 31/12/9999

“2bn characters”

Any object reference

Avoid

Page 20: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Suggest suitable variable names and types for variables representing:• GDP of a country

• Client name

• Client reference number

• Price of an item of stock

• Number of items in stock

• Number of staff in a department

• Agent’s commission rate

• Invoice due date

• Invoice state (paid or unpaid)

Page 21: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Open week3.xls

Open the VBE and look at the Macro

Orders

• Why won't it run?

• Can you fix the errors?

Page 22: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Variables are declared to exist within a program A variable can be initialised with a value A variable can have different value while a

program runs

Dim xxxx As type• Dim stands for dimension

• As assigns type

Dim x, y, z as integer (wrong)Dim x as integer, y as integer, z as integer (correct)

Page 23: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Sub Example()

Dim x As Byte

x = InputBox (“Enter a number between 1 and 10”)

MsgBox x

End Sub

Use Option Explicit at the head of a module to

force variable declaration

You can automatically use Option Explicit

• Tools>Options>Require variable declaration

Page 24: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Variable on the LHS, Value on the RHS

x = 1 the value 1 is assigned to x

SalesRegion = “North West”• use double quotes when assigning string variables

NextFinYear = #1-April-2009#• Use # to enclose the value of a date, NB date format

defaults to US (very inconvenient!)

Page 25: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

DeliveryDate = OrderDate + 3

y = x• a variable y is assigned the value of x

OrderTotal = Subtotal * VatRate

OrderNo = OrderNo + 1• increases the value of a variable called OrderNo by 1

(called incrementing)

y = Range(“B3”).Value

Page 26: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Operator Operation Example Answer

+ Add 5+4 9

- Subtract 7-2 5

* Multiply 3*5 15

/ Divide 10/4 2.5

\ N1 \ N2 - integer division 15\4 3

Mod X Mod Y returns remainder 10 mod 3 1

^ X ^ Y gives the value of X raised to the power of Y

2^3 8

Page 27: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Sub example1()

'declare variablesDim x as integer, y as integer, z as integer

' assign values to variables

x = 3y = 4z = x + y

' output resultMsgbox z

End sub

Page 28: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

sub enterNumbers ()

Dim Number as Integer

number = InputBox("Enter number under 5000", "Enter_

numeric data")

number = number * 2

MsgBox "The number multiplied by 2 is " & number, _

, ,"Greeting Box"

End Sub

Page 29: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Concatenation operator & is used to join things together e.g. a number to text. For example:

MsgBox "You will be paid " & payrate & " per hour"

• “&” concatenates string and numeric variables, so you should use it if you want to combine a string and a number

There is also + but this can only concatenate one string to another; if you use it to concatenate a number to text you will get a run-time error

Page 30: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Introductory

Reading cells

Page 31: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Used for a value that recurs but never

changes throughout the programme

Const taxRate = 0.28

Can now refer to taxRate during the

programme and can easily update the

value by changing this one line of code

Page 32: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Prefix vb or xl in the Object library• ColorConstants

• Excel Direction

Page 33: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

If condition ThendoSomething

Elseif anotherCondition ThendoSomethingElse

ElseIf anotherCondition ThendoSomethingElse

ElsedoSomethingElse

End If

= equal to

< less than

<= less than or equal to

> greater than

>= greater than or equal to

<> not equal to

Page 34: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Sub Profit_Loss ()

Dim profit As singleprofit = Range("C1").Value

If profit > 0 ThenMsgBox "You have made a profit"

ElseIf profit = 0 ThenMsgBox "You have broken even"

ElseMsgBox "you have made a loss"

End IfEnd Sub

Page 35: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Sub Profit_Loss ()

If Range("C1").Value > 0 ThenMsgBox "You have made a profit"

ElseIf Range("C1").Value = 0 ThenMsgBox "You have broken even"

ElseMsgBox "you have made a loss"

End IfEnd Sub

Page 36: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Pebbles and Muffins

Page 37: Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week02/Term2/Week02/Week2.pdf · • The line is coloured green and ignored by VBA 2. Indent consistently ... Dim xxxx

Assessed Exercise Variables and if

statements

Using Ranges in VBA