Sei sulla pagina 1di 73

Francis Lai

De La Salle University – Manila


francis.lai@delasalle.ph
Outline
 Text-to-columns
 Grouping
 Name Definition
 Data Validation
 Pivot Table
 Macro
 Workbook Security
Text-To-Columns
 Used to distribute cell contents into other cells
 Can be used to format contents of a Comma Separated
Value (CSV) file
Grouping
 Temporary way of hiding data
 Hidden set of data can easily be unhidden
Name Definition and Usage
 Creates Names/Variable to rename cells or range of
cells
 Useful for long/complicated formulas
Data Validation
 Used to limit the input type of a cell into the following:
 Any Value
 Whole Numbers
 Decimal Numbers
 List
 Date
 Time
 Text with specified length
 Custom Formula
Data Validation
 Can you create a varying list that is dependent on
another list?
 Example:
First Status Second Status
In Customs
Delayed
In Transit
Just Arrived
Processing
In Office
Warehouse
Processed
Shipped
Pivot Table
Before you start to
work with a PivotTable
report, take a look at
your Excel worksheet
to make sure it’s well
prepared for the
report.

When you create a PivotTable report, each column of


source data becomes a field that you can use in the report.

Fields summarize multiple rows of information from the


source data.
Pivot Table
The names of the fields
for the report come
from the column titles
in your source data. So
be sure you have names
for each column across
the first row of the
worksheet in the
source data.

The remaining rows below the headings should contain similar items in the same
column.

For example, text should be in one column, numbers in another column, and dates in
another column. In other words, a column that contains numbers should not contain
text, and so on.
Pivot Table
Finally, there should be
no empty columns
within the data that
you’re using for the
PivotTable report.

It’s also best if there are no empty rows.

For example, blank rows that are used to separate one


block of data from another should be removed.
Pivot Table
Here’s how to get
started with a
PivotTable report.

You use the Create


PivotTable dialog box,
shown here.

1. When the data is ready, click anywhere in the data.


2. On the Insert tab, in the Tables group, click
PivotTable, and then click PivotTable again. The
Create PivotTable dialog box opens.
Pivot Table
Here’s how to get
started with a
PivotTable report.

You use the Create


PivotTable dialog box,
shown here.

3. The Select a table or range option is already selected


for you. The Table/Range box shows the range of the
selected data, which you can change if you want.

4. Click OK.
Pivot Table
This is what you see in
the new worksheet
after you close the
Create PivotTable
dialog box.

1 On one side is the layout area ready for the PivotTable report.
On the other side is the PivotTable Field List. This list shows the column titles
from the source data. As mentioned earlier, each title is a field: Country,
2 Salesperson, and so on.
Pivot Table
You create the
PivotTable report by
moving any of the
fields shown in the
PivotTable Field List
to the layout area.

To do this, either select the check box next to the field


name, or right-click a field name and then select a
location to move the field to.
Pivot Table
Now you’re ready to
build the PivotTable
report. The fields you
select for the report
depend on what you
want to know.

To start: How much


has each person sold?

To get the answer, you need data about the salespeople and their sales numbers.

So in the PivotTable Field List, you’ll select the check boxes next to the
Salesperson and Order Amount fields. Excel then places each field in a default
area of the layout.
Pivot Table
The gray table at the
illustration’s far left
provides a conceptual
view of how the report
will automatically
appear based on the
fields you select.

Here are details.

The data in the Salesperson field (the salespeople’s names), which doesn’t contain
numbers, is displayed as rows on the left side of the report.

The data in the Order Amount field, which does contain numbers, correctly shows
up in an area to the right.
Pivot Table
It doesn’t matter
whether you select the
check box next to the
Salesperson field
before or after the
Order Amount field.
Excel automatically
puts them in the right
place every time.

Fields without numbers will land on the left, and fields


with numbers will land on the right, regardless of the
order in which you select them.
Pivot Table
That’s it. With just two
mouse clicks, you can
see at a glance how
much each salesperson
sold.
And here are a couple
of parting tips on the
topic.

First, it’s fine to stop with just one or two questions answered; the report doesn’t have
to be complex to be useful. PivotTable reports can offer a fast way to get a simple
answer.

Next, don’t worry about building a report incorrectly. Excel makes it easy to try things
out and see how data looks in different areas of the report.
Pivot Table
Now you know how
much each salesperson
sold. But the source
data lays out data
about salespeople in
two countries, Canada
and the United States.

So another question you might ask is: What are the sales amounts for each
salesperson by country?

To get the answer, you can add the Country field to the PivotTable report as a report
filter. You use a report filter to focus on a subset of data in the report, often a product
line, a time span, or a geographic region.
Pivot Table
By using the Country
field as a report filter,
you can see a separate
report for Canada or
the United States, or
you can see sales for
both countries
together.

To do this, right-click the Country field in the


PivotTable Field List, click Add to Report Filter, and
then take it from there.
Pivot Table
The original source
data has a column of
Order Date
information, so there is
an Order Date field
on the PivotTable
Field List.

This means you can find the sales by date for each salesperson.

To find out, you’ll add the Order Date field to your report and then use the Grouping
dialog box to group the date data and create a more manageable view.
Pivot Table
Though the PivotTable
report has answered
your questions, it takes
a little work to read the
entire report—you
have to scroll down the
page to see all the data.

So you can pivot the report to get a different view that’s easier to read.

When you pivot a report, you transpose the vertical or horizontal view of a field,
moving rows to the column area or moving columns to the row area. It’s easy to do.
Pivot Table
If you prefer to build a
PivotTable report by
using the drag-and-
drop method, as you
could in previous
versions of Excel,
there’s still a way to do
that.

There are four boxes at the bottom of the PivotTable Field List: Report Filter, Row
Labels, Column Labels, and Values. You can drag fields to these boxes to designate
how the fields are used in the report.

The picture shows how you can drag the Order Amount field from the Column
Labels to the Values box to add that field to the Values area of the report.
What are macros?
 Macros are very powerful tools that YOU create to improve
the performance of Excel
 With a simple recorded macros you would only have to hit
one key instead of 10 and a series of things would happen
like
1. enter a value
2. move three cells down
3. enter a formula
4. move three cells left
5. make the font red
 Behind the scene these macros were recorded using a
programming language called VBA (Visual Basic for
Applications)
What can be done with macros?
 Automation, automation and automation.
 with simple macros you will get Excel to accomplish
repetitive tasks over and over again. A macro will
complete in seconds what would take you hours.

 90% of the data analysis and reporting is done with


Excel in small, medium and large enterprises. Even the
large enterprises that spend millions of dollars in
databases and centralized programs (accounting, sales,
production, etc) end up analyzing their data with
Excel.
Who can use it?
 Anyone who uses Excel
 Anyone who’s tired of routine Excel Tasks
 Report Analyst
AD&SI Wiki U
Based on HP Standard Slides / HP Confidential
Vocabulary
 Excel Macros: also known as Excel VBA, Macro command
performed by Excel rather than you.
 VBA Procedure: instructions that you want the computer to
execute.
 Objects: building blocks of your Excel projects they are:
 Application (Excel)
 Workbooks
 Worksheets
 Cells
 Ranges
 Charts
 Drawings
 Controls (command buttons, text boxes, list boxes, etc.)
Vocabulary
 Methods: Think of the verb to do. You might want an object to
close, to open, to be copied or pasted, etc.
(ActiveWorkbook.Close, ActiveCell.Copy). Again Excel will tell
you when you are trying to use a method that doesn't apply to
the object that you are working with.
 Functions: You can and you will use all the Excel functions
within your VBA code but you can also use VBA functions like
UCASE, LCASE, NOW(), etc. (Activecell.Value=NOW())...
 Statements: IF..THEN, DO...LOOP, FOR...NEXT, WITH...END
WITH, EXIT, FOR, EXIT DO, EXIT SUB
 Events: For a procedure to start and be executed an event must
happen. One event that everybody knows about is the click on
the button. Other events include opening a workbook, activating
a sheet, modifying the value of a cell, etc... .
vocabulary
 A VBA project can comprise four types of components:
a workbook, worksheets, modules and userforms
 Workbooks: A workbook is an Excel file
(something.xls) also called spreadsheet. The object
"ThisWorkbook" is the workbook within which the
macro is created. The code ThisWorkbook.Close will
close the workbook within which the active macro is
running.
 Worksheets: Sheets/tabs/ worksheet
vocabulary
 Modules: It is a kind of a file in which you store most
of your VBA procedures (macros). Modules are
created and named in the Visual Basic Editor.
 UserForms: User interface in form of windows GUI
 Controls: command buttons / check boxes / labels /
text boxes / list boxes/ option buttons and other
gizmos that you put on userforms or worksheets.
Creating a Macro
 USING EXCEL
 Under View Ribbon > Macros> View Macros
or
 Press ALT + F11
Parts of the Visual Basic Editor

Project
Explorer

Code

Properties
Window
Creating a macro
 While In The Visual Basic Editor
Go To
Insert > Module
Creating a Macro
 In The Module Window, type the following

Sub myMacro()
MsgBox "Hello World!"
End Sub
Creating a macro
In The Module Window

Click the Run button


Or
Press F5
Or Go To
Run > Run Sub / UserForm
Creating a macro
 Your first program
Objects and Collections
 Objects
 Fundamental building blocks of Visual Basic
 Object is a special type of variable that contains both
data and codes.

 Collection
 Group of objects of the same class
 Sample: Workbook, Worksheet, Sheet, and Range
Variables and Structures
 Variables
 Holds values that can be altered by program
 Variable Types
 Standard numeric or text
 Excel Application Specific
VARIABLE TYPES
Variable Type Description

Boolean True or False

Integer Whole numbers from −32,768 to 32,767

Long Whole numbers from −2,147,483,648 to 2,147,483,647

Currency Decimal numbers -922,337,203,685,477.5808 to


922,337,203,685,477.5807
Single These are floating point values, providing around six
significant figures of accuracy
Double These are floating point values, providing around 14
significant figures of accuracy
VARIABLE TYPES
Variable Type Description
Date A date variable is composed of two floating pointing values,
one containing a date and the other containing the time of day.

String Variable length character strings

Variant A variant variable can contain any of the above data types.
Variant data variables change their type dynamically according
to what is stored in them. Note that variables are assumed to be
Variant unless specifically declared to be something else.
Variables and Structures
 Arrays
 All data part of the array are of on multiple data type
 Set of sequentially indexed elements having the same intrinsic data
type
 Single- / Multi-dimensional
 Single-dimensional Array: Dim Arr(4)
 Multi-dimensional Array: Dim Arr(2, 2)

 Lbound - find the lower limit of an array dimension


 Ubound – find the largest available subscript of an array
dimension
 ReDim - used to size or resize a dynamic array that has already
been formally declared.
 Example: Redim Arr(6)
EXAMPLE
Option Base 1
Sub assignArray( )
Dim Arr(5)
Arr(1) = “Jan”
Arr(2) = “Feb”
Arr(3) = “Mar”
Arr(4) = “Apr”
Arr(5) = “May”

Msgbox Arr(1) & "-" & Arr(2) & "-" & Arr(3) &
"-" & Arr(4) & "-" & Arr(5)
End Sub
Using LBound and UBound
Sub arrayTest2()
Dim i As Integer
Dim intMyScores(10) As Integer

For i = LBound(intMyScores) To
UBound(intMyScores)
intMyScores(i) = i
Next
End Sub
Variables and Structures
 Collection
 A better choice for a data structure
 Is not dimensioned
 Holds multiple data types

 Example of Collection
 Workbooks
 Worksheets
 Range / Cells
Modules and Procedures
 Module - a container for procedures
 Procedure - unit of code enclosed between either
 the Sub and End Sub statements
 the Function and End Function statements
Modules and Procedures
Sub ShowTime()
Range("C1") = Now()
End Sub

Function sumNo(x, y)
sumNo = x + y
End Function
Modules and Procedures

MODULE

PROCEDURE
Calling Sub Procedures and
Function
 There are two ways to call a sub procedure. The following
example shows how a sub procedure can be called by other sub
procedures.

Sub z(a)
MsgBox a
End Sub

Sub x()
Call z("ABC")
End Sub
Sub y()
z "ABC"
End Sub
Calling Sub Procedures and
Function
Function sumNo(x, y)
sumNo = x + y
End Function

Sub ShowSum()
Msgbox sumNo(3,5)
End Sub

Module1.ShowSum
Methods and Properties
 Property
 built-in or user-defined characteristic of the object

 Method
 an action that you perform with an object
Logical Operators
Logical Description Rule Example
Operator

AND Both operands X AND FALSE = RAINING AND


must be satisfied FALSE MORNING

OR At least one of the X OR TRUE = RAINING OR


operands must be TRUE MORNING
satisfied

NOT Performs the NOT FALSE = NOT RAINING


logical negation TRUE
NOT TRUE =
FALSE
RELATIONAL OPERATORS
Relational Operator Description Example

< Less than 4 <5

> Greater than 4>5

<= Less than or equal to 4 <= 5

>= Greater than or equal to 4 >= 5

= Equal to 4=5

<> Not equal to 4 <> 5


Decision Structures
 If ... Then ... Else and If ... Then ... ElseIf

If (userGuess > age) Then


MsgBox ("Too high!")
MsgBox ("The answer is " & age)
ElseIf (userGuess < age) Then
MsgBox ("Too low!")
MsgBox ("The answer is " & age)
Else
MsgBox ("You got it!")
End If
Decision Structures
 Select Case … End Select

Select Case userGuess


Case Is > age
MsgBox ("Too high!")
MsgBox ("The answer is " & age)
Case Is < age
MsgBox ("Too low!")
MsgBox ("The answer is " & age)
Case Else
MsgBox ("You got it!")
End Select
Loop Structures
 For … Next (With Step/No Step)  number of
repetitions is known

For n = 1 To 10 Step 2
t = t + n
Range(“A1”).Value = t
Next n

MsgBox "The total is" & t


Loop Structures
 Do While … Loop  conditional test first then execute
as long as a specific condition is true

Do While Not IsEmpty(ActiveCell.Value)


ActiveCell.Value = ActiveCell.Value * 2
ActiveCell.Offset(1, 0).Select
Loop
Loop Structures
 Do … Loop While  execute loop at least once and
then conditional test

Do
ActiveCell.Value = ActiveCell.Value * 3
ActiveCell.Offset(1, 0).Select
Loop While Not IsEmpty(ActiveCell.Value)
Loop Structures
 Do Until … Loop  program continue to loop until the
condition is true

Do Until IsEmpty(ActiveCell.Value)
ActiveCell.Value = ActiveCell.Value * 3
ActiveCell.Offset(1, 0).Select
Loop
Loop Structures
 Do Loop … Until  condition is tested at the end of
the loop

Do
ActiveCell.Value = ActiveCell.Value * 3
ActiveCell.Offset(1, 0).Select
Loop Until IsEmpty(ActiveCell.Value)
Passing Arguments
 Argument Passing ByVal
 procedure cannot modify the variable itself
 Argument Passing ByRef
 the procedure can modify the variable itself

Example 1 Example2
Sub TestPassing1() Sub TestPassing2()
Dim y As Integer Dim y As Integer
y = 50 y = 50
AddNo1 y AddNo2 y
MsgBox y MsgBox y
End Sub End Sub

Sub AddNo1(ByRef x As Integer) Sub AddNo2(ByVal x As Integer)


x = x + 10 x = x + 10
End Sub End Sub
Recording a macro
 Select Record New Macro under Tools -> Macro
 In the Record Macro dialog box, type
"SetBackgroundColor" in the Macro Name textbox to set
the macro name. Leave all other option by default then
click the OK button. This will start the macro recording
 In the Background Color Panel, select the light Yellow color
box. This action will set the background color of the
current cell (A1) in light yellow color.
 To stop the macro recording, click the Stop button (the
navy blue rectangle) on the Macro Recorder toolbar.
 View the generated code
 Run the newly created macro
 Modify the macro then run again
Recording a macro
 Excel VBA Macro Recorder
 Simple Macros
 Extraneous Commands Generated
 No looping and/or conditional statements generated
 Records absolute references to cell by default
Recording a macro
 Select Record New Macro under Tools -> Macro
 In the Record Macro dialog box, type "SetPage" in the
Macro Name textbox to set the macro name (leave all
other option by default then click the OK button)
 Choose File -> Page Setup, then select landscape
option
 To stop the macro recording, click the Stop button (the
navy blue rectangle) on the Macro Recorder toolbar
Exercise 1
 Create a macro that will do the following:
 Concatenate the value of Column A and Column B with
respect to their rows
 Write this value to Column C of the respective row
 Determine if this value has a string length greater than
50 (Result should be in Column D)
 A message box must pop up reporting the following:
 Number of entries that have more than 50 characters
 Number of entries that have less than or equal to 50
characters
Exercise 2
 Create a procedure that calls a function that computes
the factorial of a number entered in cell A1 of Sheet 1
 Display the result using Msgbox
 Use passing argument syntax
Tips and tricks
 If you do not know the code/syntax, record it and tweak the code
later! 
 Be resourceful – Google it! Type keyword VBA when searching.
 Always use “Option Explicit” at the beginning of each module
 Use error handlers:
 On Error GoTo [label] - VBA continue execution at the specified
line.
 On Error Resume Next - VBA ignores all errors and continue to
execute until end.
 On Error GoTo 0 - VBA resumes its normal error checking behavior.
Very useful when you want to remove error handling in your
procedure.
 Take caution when referencing with objects
TIPS and TRICKS
 For improved performance, you may opt to disable events or set to
manual some properties such as:
 Application.Screenupdating
 Application.Calculation
 Application.EnableEvents
 For debugging, use breaks, bookmark, add watch, immediate window
 F8 for single-line run of code, F5 to run all codes until a break is seen or
until end of procedure
 Use Sheet Code names. These can be seen in the "Project Explorer"
(Ctr+R). Get into this habit as the Code name never changes, even if
the sheet is renamed or moved within the workbook
 Use ThisWorkbook.
 E.g. ThisWorkbook.Name - This will always return the name of the
workbook that is hosting the code
Workbook Security
 Protect Worksheet
 Protect Workbook
 Protect VBA Macro Source Code

Potrebbero piacerti anche