Sei sulla pagina 1di 44

Automating your Spreadsheets,

Using Excel and VBA


Part 1
HR Value, LLC
Delivering exceptional results
with the click of a mouse

Roy Farrell Kenn Williamson


Managing Director Developer
RoyFarrell@4hrv.com HR Value, LLC
www.4hrv.com
(614) 266-5926
1
Discussion Outline -
Automating your Spreadsheets
Technology is the overlooked barrier to being a successful business partner. We will
introduce you to a powerful technology solution sitting on your computer.

VBA could be part of a strategy that uses the best of your technology:
– use your HRIS and other systems for their core functions
– use the powerful functionality of Excel and VBA to give you all the good stuff

We will discuss
1. The business case
2. An alternative technology strategy, using Excel and VBA
3. A model of a salary planning tool
4. Specific examples of VBA code used to automate some functions in this tool

While we only have an hour and this is by no means a complete discussion of VBA, it will
present a starting point to solutions you may not have know existed. Part 2 – date not yet
scheduled – will focus on the development of a GUI in Excel

2
HR Value What We Do
We help companies with custom solutions in two key areas:
• Business Analytics and Information management
• Automation of time intensive processes
We take the most complex process and give clients “click of the mouse” ease, all
at a cost that is a fraction of system modifications or additional software. Excel
and VBA allows construction of sophisticated business tools - a pre/post
information processor for business data, or the ability to create sophisticated
‘turn-key’ solutions that rival and exceed million dollar alternatives.
You can easily access data from multiple systems, HRIS, payroll or outsourced
solutions, and refresh that data at any time. You can access even the most
complex analysis, reports and charts. All with tools that are sitting- largely
underutilized - on their desktops.
We add value, and save our clients time and money

This is not a sales pitch. We want to introduce you to an Excel you may
not know exists, by using some very specific examples. We provide help in
3
these areas, but everything discussed here is available on your desktop.
Administrative and compliance activities
dominate HRIS systems and dollars

Ed Lawler penned an article that points to the root


cause of the problem. Dr. Lawler asks us to “give
HR more respect” but recognizes that “the group
with the expertise to help the organization better
manage and utilize people—the human-resources
department—often is too mired in administrative
tasks to tackle higher-value work.”

Edward E. Lawler III, The HR Department: Give It More Respect, MIT Sloan Management
Review, Posted March 10, 2008 http://sloanreview.mit.edu/wsj/insight/hr/2008/03/10/

4
How do you break the cycle?
The good Dr. Lawler never quite explains how the
HR staff “spend less time processing benefits
requests and more time being the expert
resource on the state of the organization's work
force and its ability to perform” but his perception
is spot on – HR is caught in a death spiral of
compliance and administration.
The question remains – WHY?
Edward E. Lawler III, The HR Department: Give It More Respect, MIT Sloan Management
Review, Posted March 10, 2008 http://sloanreview.mit.edu/wsj/insight/hr/2008/03/10/

5
HR Value Point of View
• Core HR technology solutions are built to address the very important
compliance and administration tasks of their profession, largely driven by
Payroll, Benefits, and record keeping. It is very difficult to develop robust
planning tools or administer multiple approaches with a payroll system
• Even when using 'The Best’ software, you are tied to the capabilities and
functionality of your HRIS system that often delivers a rigid and plain vanilla
process. This is not what leadership wants
• There is no competitive advantage in doing things just like the competition
• Add-on packages claim to solve your problems, but you soon discover you
simply trade one set of limitations for another, or create information silos
that restrict meaningful analysis - all at a considerable expense
• And there is little interest in spending more money on expensive systems or
system modifications that cannot demonstrate a positive ROI
6
Compensation Decision Making

Effective compensation decisions follow a proven evaluation and development process.

Total target compensation levels that


consider market rates and internal
company value.

Market
Pay
Ongoing program management, Salary and incentive ratios that
performance evaluation, and reflect the business role and
planning. competitive environment.

Performance Pay Mix


Policies and process to manage & Evaluation Incentive for top performers and
program operations according plan entry points that differentiate
to the design. for achievement.

Business Upside &


Governance Threshold
Roles

Market-based objectives, set to enable Objectives Measures & Performance metrics and weights
value-adding organization performance. &Goals Priorities that clearly communicate business
priorities.

Mechanics Technology that link pay to


performance across all
attainment levels.
Barriers to effective Compensation Decision Making
Structural Challenges: Rewards Challenges:
- Financial results are continually - Rewards tools used once a year
changing through the rewards cycle - Managers ‘messing up’ data in spreadsheets
- Reorganizations - Managing the flow of data in the company
- Lose connection between - Preparing reports on a timely basis
rewards budgets and financials - Market
Multiple approval processes in different parts of the
- Transfers and proration Pay
company
- Data in multiple systems - “Total Rewards” data in different systems
- Sales data in multiple systems • Base Pay is fairly easy, it is on the HRIS
Performance
- Compensation Committee & Evaluation • Commissions
Pay Mix calculated in separate system
schedules • Incentive Awards are largely done with
- Gender and ethnicity reviews spreadsheets
- Real timing challenges • Stock and Long
Business Upside & Incentives are done by a
Term
Governance Threshold
Roles
third party
• Health Benefits are done by a fourth party
• Life Insurance is done by a fifth party
Objectives Measures &
&Goals • LTD and STD is done by a sixth party
Priorities
• Retirement Plans are done by a seventh party,
and is complicated because you froze your DB
plan and replaced it with an enhanced DC
Mechanics
savings plan
The technology concerns are
frightening …
These tasks need to be
accomplished, and your
day becomes consumed
with paperwork or
repetitive spreadsheets.
This leads to higher costs
and lower productivity.

9
C-Suite credibility requires the ability to
model pay and performance options
quickly and clearly for a busy, non-
specialist audience.
software solutions
without limits at a
fraction of the cost of
Now, imagine… alternatives

Spreadsheets provide all the flexibility


and you need to administer even
You can automate them. the
most complex plans, but they can
quickly become unwieldy.
Let us introduce to the Excel you
never knew existed
10
It doesn’t have to be this complicated
Data ETL Enterprise Data Warehouse Real Time
Sources Architecture Analytics
Staging Area
HRIS Extract,
Virtual
Transform Operational Data Store Reporting/
Sales and Load Analytics
Data Warehouse
Stock Virtual
Options Virtual Data Dashboard

T&D Massive Parallel


Virtual
Services – Web/Data
Finance Applications
Messaging

Relational
Pensions

401k
PORTAL
Internal

External
It doesn’t have to be this complicated
Data Excel and other Microsoft Excel and VBA provide
Sources Office products utilize a the capability to rapidly
programming language called integrate information
HRIS
Visual Basic for from different
Applications or VBA. applications, without a
Sales
Stock
Excel and VBA integration costly infrastructure.
Options
features come pre-built, so
using Excel as an information
T &&DD
T integration platform avoids
the time and cost of
Finance
developing applications from
scratch that perform the Unfortunately, many
Pensions
same
VBA construction of sophisticatedofbusiness
tasks.
allows Excel's features
tools are
401k • a pre/post information processor forstill largelydata
business unknown
• automation of time intensive tasks or dismissed
Internal prematurely

External 12
Excel comes standard with tools that
can provide sophisticated task support
Information analysis, organization and
Excel to the rescue!
processing
Microsoft Excel fills the niche of being
able to perform complex business Report and form generation
analysis tasks or automate business Creating and combining planning tools
tasks rapidly and cost effectively
Import and combine data from multiple
Excel with VBA is one of the most databases
powerful, flexible packages on the
market today Integrate information from different
applications
Excel has tremendous capabilities that
can help streamline your business Charting and Modeling
tasks Budgeting and Planning
Unfortunately, many of Excel's “What if” scenarios
features are still largely unknown or
dismissed prematurely Accruals

And anything else you can imagine


13
Develop powerful and sophisticated
business tools

You can create:


1. Graphic User “click of the mouse” interface
2. Flawless Workflow
3. “Foolproof” process
4. Tools maintained by non-technical users

14
1. GUI Design –
Intuitive Graphic Interfaces

1. Excel has built-in capabilities, which


allow elaborate graphical user
interfaces (GUI’s) to be developed.
2. The Excel controls used to develop
these interfaces are easy to employ,
basically just draw them and set a
couple of options.
3. Because GUI’s are easy to
construct in Excel, Excel can be
utilized very effectively and cheaply
as a pre/post information processor
for business data
4. And most important, they can be
used to build a flawless and
foolproof workflow.

15
2. Workflow managed by Menu functions, tailored
to your requirements– no compromises
“Click of the Mouse” ease

Tool Creation is fully Automated


Consolidate data – no “Cut & Paste”
Import new data from multiple sources
Reports dynamically updated
Unlimited Planning and Budgeting
functionality

16
3. Workflow creates a “foolproof” process

Users cannot change tools:

Separate User and Admin menus


Editing functions disabled
Core data cannot be changed
Calculations cannot be altered
Documents cannot be altered
Database updated automatically
Reports automatically updated

17
4. “Non-Technical” users can update tables,
without IT or “power user” intervention

Administrator can change all


plan parameters without IT
support or programming

18
VBA allows construction of
sophisticated business tools in Excel
Need to understand:
The basic principles of the VBA
language.
The concept of a VBA project.
The concept of a VBA procedure.
How to manage and use VBA
modules that store VBA code
The operation of the VBA Editor

The purpose of presenting these concepts is not to turn


business professionals into full time software
developers. The opposite is the case. The main reason
for a business professional to use Excel and its
capabilities are because they're pre-built.
19
VBA language is Object Oriented
VBA is an Object oriented language, different from a procedural language.

“Kick the Ball” in English

translates to Ball.Kick in VBA

You can then add parameters. “Kick the Soccer ball hard, high, and to the left”

Becomes Ball (“Soccer”).Kick Direction:=Left, Force:=Hard, Elevation:=High

VBA Component Analogous to Comments


Object Noun
Collection Plural Noun Usually defines which object: Worksheets(1)
Method Verb Object.Method (Ball.Kick)
Parameter Adverb Lists parameters after the method. Separate the parameter
from its value with := (Ball.Kick.Direction:=Left)

Property Adjective You can set a property. Activecell.height = 10 or you can


20
query the value of a property x = activecell.height
A VBA project is a collection of Excel objects,
references, modules and userforms
• A VBA project can be created in different Microsoft Office products.

• When a new workbook is created in Excel, a new VBA project is


automatically created and associated with that workbook file

• A workbook can contain only 1 VBA project

• You add the elements to a VBA project when you need them.

• Whatever Microsoft application a VBA project is constructed in (i.e.


Excel, MS Word, MS PowerPoint…etc), that application is used to
launch the project. When a workbook file is saved, its associated
project is automatically saved. When a workbook file is closed, its
associated project is closed.

21
VBA Procedure

Need to understand: A procedure is a named sequence of


The basic principles of the VBA statements that are executed as a unit. VBA
language. procedures are used to perform tasks such as
communicating with databases, calculating
The concept of a VBA project.
equations…etc.
The concept of a VBA procedure.
How to manage and use VBA A VBA procedure consists of a procedure
modules that store VBA code declaration statement and ending
The basic operation of the VBA statement with statements in between. The
Editor statements between a procedure’s declaration
and ending statement perform the procedure's
task.

When a procedure is executed, its statements are executed in a top-down line by


line fashion performing operations, like reading a book page.

22
VBA Modules

Standard modules are the workhorse of a VBA project.

They store and organize procedures that are used to perform tasks like
controlling Excel, communicating with databases, calculating equations…etc.

We will show specific examples of code to demonstrate modules.

If you want to receive the excel files with these examples, please complete the
feedback form and indicate so. Include your name and email address.

Or send an email directly to


royfarrell@4hrv.com

23
VBA Editor

VBA projects are created, edited and debugged in the VBA Editor.

In order to create VBA projects, a designer must have a basic


understanding of the VBA Editor.

The VBA Editor is activated from the Excel ribbon and selecting Developer
then Visual Basic.

You could also press Alt + F11

You can toggle between Excel and VBA by pressing Alt + F11

24
VBA Editor window contains many
windows that can be displayed at once.

The Project window lists the


currently open VBA projects
and their elements. You
navigate through projects in
the Editor by using the
Project window.
A Code window
displays a module in
The Properties window the Editor allowing
displays the properties of the you to write and edit
currently active object. Here, its code. Multiple
Module1 is selected and the Code windows may
name property of that object be displayed and
appears in the window. arranged in the VBA
Editor at once.

25
VBA comes standard with a set of
built-in debugging tools

A designer uses these tools in a detective role, stepping through a procedure’s code line
by line executing them, viewing their results and detecting mistakes along the way.
The following list presents the code error types that are encountered when developing
procedures:
Language . Language errors result when statements are constructed incorrectly. Some
common language errors are:
• Improper use of parenthesis
• Forgetting to type an End or Next keyword
• Misspelling a keyword
VBA will detect these errors before the code is executed. They are caught during the
compilation phase or typing phase (indicated by red syntax).
Run-time errors. Run-time errors occur when a statement attempts an impossible
operation. Some common run time errors include identifying objects that do not exist or
dividing in an expression by 0. VBA detects these errors during code execution.
Logical errors. Logical errors occur when an executing procedure does not do what it is
supposed to do. The syntax is correct and performs operations, just not the expected
ones. Errors of this nature cannot be easily detected by just executing the code.
26
VBA comes with tools to speed your
work – IntelliSense

1. Typed 'sh' with the intention to


refer to Sheet1 object. Then clicked
'Complete Word' button.

2. This shows what IntelliSense gave


as a result. I double-click Sheet1

3. After Sheet1 was in place I


typed '.' (dot) to see/select a
property/method of the
Sheet1 object. I got the list of
property/method immediately
after typing the dot.

27
VBA Code Examples

VBA allows to build powerful and sophisticated applications that rival stand alone
applications costing hundreds of thousands or millions of dollars.

We will show you a stand alone salary planning tool, and show you some of the
VBA code that makes all of it possible. These functions could be part of a library
that could be included in spreadsheets for efficiencies, or part of a turnkey solution.
• Disable Cut/Copy/Paste
• Add a sort button
• Import file
• Loop
• Color rows
If you want to receive the excel files with these examples, please complete the feedback
form and indicate so. Be sure to include your name and email address.

Or send an email directly to


royfarrell@4hrv.com

28
Example : Salary Planning to your exact
specifications

Clipper Windpower asked us to build a salary planning tool.

Salary administration was complicated by a number of factors:


1. Multiple locations throughout the US and International locations
2. Two different performance rating systems, one for Salaried and
Office personnel, and another for Operations
3. The Parent Company maintained the performance management
system, but didn’t have a salary tool
4. The company operates in a rapidly changing economic environment

29
Break to live example of tool

Show the VBA examples

30
Salary Tool - Automated with VBA
Disable Cut/Copy/Paste
To prevent managers from ‘messing up’
the Data, we disable certain dangerous
Functionality. They ‘click the mouse’
for a flawless workflow
Import files
Multiple files can be imported Loop
with a click of the mouse to Looping is not available in the Macro Recorder,
refresh the data any time But is necessary for repetitive functions, such as:
- Creating Multiple planning tools
- Parsing Data
- Combining completed tools

Add sort buttons


To prevent managers from ‘messing up’ Color Rows
the data, we disable the sort function, To help managers navigate rows of
but give them ‘click of the mouse’ sorts Data, we color coded the two types
31
of employees – Salaried and Operations
VBA code for a basic for…next loop explained

The first line names the


subroutine (sub) In this
example it is “SampleLoop”

“Dim” means dimension.


This is the keyword for a
variable declaration. It is
telling the program that “i”
Press the ‘Alt’ and ‘F11’ is an integer.
key to open the VBA
Editor and click on the
Basic Loop Module, and
display the code in the
Code Window
VBA code for a basic for…next loop explained

There are 8 basic data types:


Byte, Short, Integer, Long,
Boolean, Single, Double, and
String.

For most purposes you will use:


Integer to represent a whole
number.
Double for a decimal number.
Boolean for a true/false.
String for characters and words.
VBA code for a basic for…next loop explained

This block is the for…next loop.


“For i = 2 to 10” means to do the
code in the loop for all the integer
values of “i” between 2 and 10. At
the end of the loop is the Next
statement which means to go to
the next value of “i”.

The code in the loop “Cells(i, i).value = i” means


To put the value of “i” into the cell at (i,i).
For VBA cell “A1” is cell (1,1) and cell “A2” is cell
(2,1).
Cell “B1” is (2,1) and cell “B2” is cell (2,2).
VBA code for a basic for…next loop explained

So this code will print 2 in cell(2,2) or


“B2” then 3 in cell(3,3) or “C3” etc until it
gets to 10 then when it hits the “next i”
the value is 11 so it stops looping.

At the end of the sub you


have the end sub statement
which shows the subroutine
is finished.
VBA code for ColorRowsModule explained
Here we have a new
subroutine (sub) called
“ColorEveryOtherRow”
We are dimensioning or
declaring two variables “i”
and “FinalRow” both as Long.
Long is like Integer only it can
hold a bigger number. Where
Integer only goes to
approximately 32,000. Long
can be as large as 2.1 billion.

Then we assign a value to “FinalRow” using the above


statement. Activesheet is the sheet currently selected.
Range(“A” & Rows.Count) means the entire column A.
End(xlUp).Row means the number of the last row with any
value in it starting from the bottom.
VBA code for ColorRowsModule explained

In this case
since the sheet
we are coloring
has 25 rows
filled in in
column A.
FinalRow takes
the value of 25.
VBA code for ColorRowsModule explained

Now we have a new


for…next loop with a couple
of changes. First it is from 8
to FinalRow. This means i
will take the values of 8 to 25.
Step means how many to
count by. In the previous
example there was no step
so it defaults to 1. This time
we are stating the step size
The code in the loop is saying to to be 2 so the values of “i” will
color the Cell(i,1) resized to 7 be 8, 10, 12, etc until they are
columns to a color number 35. This above 25.
is a light green. All of the colors
have a number assigned so you can
look it up or experiment to find the
color you want.
VBA code for ColorRowsModule explained

Sub UncolorRows is similar.


Only now we are setting the
color to “xlColorIndexNone”
which is the keyword for no fill.
VBA code for AddNewSortButton explained

Here is the code for SampleSort1.


We are declaring 2 variables with the
Dim statement. SortOrder which is
an integer and FinalRow as a Long.

Then we assign values to the variables.


SortOrder is assigned the value of cell “C1”
Another way to do the same thing would be:
FinalRow = Activesheet.Cells(1,3)
which is row 1 column 3 Or “C1”.
FinalRow is assigned a value the same way
as the previous example so it takes the value
of 24 which is the last row with values in the A
column.
VBA code for AddNewSortButton explained

Now we have an “If…then” statement.


This is a logical test. It is saying if the
value in sortorder is equal to 1 then do
the code under “Then”. Otherwise do
the code under “Else.” You don’t have to
have an “Else.” If you don’t then if the
test is false the code after then will be
skipped until the end if statement.

So since the value of SortOrder from “C1” is 1


the code after then is executed.
VBA code for AddNewSortButton explained

ActiveSheet.Range(“A3:C” & FinalRow) means A3 to C24. Then “.Sort”


tells
it to sort. “ _” means the command is continued on the next line. So it is
sorting the range using column C as the key for the sort. Which means the
data in Column C will be sorted from smallest to largest.

Key1:=ActiveSheet.Range(“C3”) means the rows will be sorted by the value in


column C.
Order1:=xlAscending means sort from smallest to largest.
Header:=xlYes means don’t sort the top row because it is a header.
Then lastly the code changes the value of “C1” to 0.
Since the logical test was true the program skips the code after the else and goes
right to the “End Sub” which shows the subroutine is over.
VBA code for AddNewSortButton explained

If we run the code again now that “C3” is set to “0.” The first if statement
is false so the code after the else statement is executed. This results in
a similar output except the sort order is descending so it will sort from
Largest to Smallest.
Too good to be true?
Questions and Discussion
If you want to receive the excel files with
these examples, please complete the
feedback form and indicate so. Be sure to
include your name and email address.
HR Value, LLC Or send an email directly to
Delivering exceptional results
with the click of a mouse royfarrell@4hrv.com

Roy Farrell
RoyFarrell@4hrv.com
www.4hrv.com
(614) 266-5926

44

Potrebbero piacerti anche