Excel Data Entry Tips and Techniques
Excel Data Entry Tips and Techniques
Excel Data Entry Tips and Techniques
The VCR buttons to the left of the sheet tabs let you navigate through
sheets.
You can right-click on the VCR buttons and from the resulting menu select
the sheet you want to view.
Tools | Options | Edit tab has a dropdown for specifying the direction the
cell pointer moves when tapping [Enter] after entering data in a cell.
The Status Bar, at the very bottom of the screen usually says Ready in the
lower lefthand corner. It provides useful information. One useful feature is
that when a block of cells is selected the SUM of the cells will appear in the
Status Bar. Right-click the SUM in the Status Bar and you can choose
another function to apply to the selected cells. You cant do anything with
this result, however, except view it in the Status Bar.
Window | Split or Window | Freeze Panes will divide the window above and
to the left of the current cell pointer position. This will allow column and/or
row headers to remain displayed in one section of the window while you
scroll and move through data in another section of the window.
You can also split the window by dragging the little gray bar above
the up arrow in the vertical scroll bar and/or the little gray bar to the
right of the right arrow in the horizontal scroll bar.
Selecting Cells
Holding [Ctrl] while using mouse selection lets you select a noncontiguous block of cells
Click the mouse once in the upper lefthand corner cell of a block of data
you want to select, then hold the [Shift] key down when you click the
mouse on the cell that defines the lower righthand corner of your block
Type the first two values in a sequence, select the two cells, click and drag
using the Fill Handle to extend the pattern
If you right-click and drag with the Fill Handle, when you release the
mouse youll be presented with a list of options for the type of
pattern/sequence you want to use.
Use a formula and then once all the data is entered, select the results, use
Edit | Copy, click in the upper lefthand corner of the destination, and use
Edit | Paste Special as Values
Excel Functions
If you have standard text to enter, maybe one of 5-10 possible entries, maybe
using the INDEX function would help.
If you want the first value, you enter 1 in B1, 3rd value in the list,
enter 3,
Once you have the values you want in Column C, Add a column, and
then use Copy | Paste Special | Values to copy the formula results to
your new column
MATCH provides the complimentary operation for INDEX given a value you
want to find, look it up in an array of possible values, and return the index number
for that values location in the array.
The INDEX function technique above can be combined with List Box or Combo
Box tools from the Forms (or Control Toolbox) toolbar.
Once youve added your List Box or Combo Box the key is to rightclick the Box and choose Format Control
In the Control tab you specify (using the example above), Input
Range: $E$1:$E$9
Choosing a value from the list will populate the cell specified in Cell
Link, say: B1
The List Box or Combo Box will only populate one cell with a value.
Close relatives of the INDEX function are VLOOKUP, HLOOKUP, and LOOKUP
For Example:
In Column B you enter the number of the value you want to pick
from the lookup table.
Formatting
Format | Conditional Formatting might be useful for error checking (invalid values
could show up formatted in red)
If you have multiple conditions specified, the conditions are evaluated
from the top of the list. Once the cell satisfies a condition it applies that
formatting and doesnt continue down through the rest of the possible
conditions.
To find cells that are formatted with Conditional Formatting use Edit | Go To |
Special and choose the Conditional formats radio button. To find cells with
2.
3.
Selecting cells and tapping the Delete key only deletes the cell contents,
equivalent to Edit | Clear | Contents
Edit | Delete chops out the cell and asks you how youd like to fill
in for the missing cells
Edit | Clear | Formats will let you delete the formatting of the cell,
e.g., borders, fonts, numeric formatting,
2 There may be certain portions of the worksheet that youd like to protect from any
possible changes. By default all the cells in the worksheet are locked but the locks
are ignored. Tools | Protection | Protect Sheet activates recognition of the locks.
Before using Protect Sheet you would unlock all the cells you want to be able to
edit when the rest of sheet is protected Select Cells, Format | Cells | Protection
tab and uncheck the default lock. Then use Tools | Protection | Protect Sheet.
If most of your cells are going to be unprotected with just a few protected
1.
2.
3.
4.
5.
Miscellaneous
Data | Text to Columns is a useful tool for separating into multiple columns
text that is currently contained in one column. For example, maybe you
have social security numbers in column A and you just need the last four
digits of the SSN. Data | Text to Columns would let you separate the SSN
into two columns.
Sometimes you may want to combine into one column text that is
currently contained in two columns. One way to do this is to write a
formula in a third column which uses the concatenation operator, the
ampersand. This formula in C1 would return the contents of A1 followed
by the contents of B1: =A1&B1
If you want to include a literal character, say a space, use the
form: =A1& &B1
The Wizard used in Data | Text to Columns is the same tool you have
available for opening text files you want to import into Excel. File | Open
with some text file will bring you to Step 1 of the Data Import Wizard.
Use File | Page Setup | Page tab | Fit to checkbox if your printout is
extending just beyond one page
Open the original workbook and choose Edit, Move Or Copy Sheet
2.
When the Move Or Copy dialog box opens, click the arrow at the
right side of the To Book list box. Choose New Book from the list.
3.
If you want to copy the sheet, select the Create A Copy check box
and click OK.
4.
Sometimes codes used in data entry need to be sorted in some order that
is not alphabetical or numeric. You can define a custom sort order in Tools |
Options | Custom Lists. Rather than Adding the list, the easiest way to
enter the values is to Import list from cells. To use your list, Data | Sort |
Options button has a dropdown where you can choose your list for the sort
order.
Users click the drop-down arrow to display a list of items from A1:A4. If a user
tries to enter something that isnt in the list, Excel rejects the entry. To add this
drop-down list to a sheet, do the following:
1.
Create the list in cells A1:A4. Similarly, you can enter the items in a single
row, such as A1:D1.
2.
Select cell E3. (You can position the drop-down list in most any cell or
even multiple cells.)
3.
4.
Choose List from the Allow options drop-down list. (See, theyre
everywhere.)
5.
Click the Source control and drag to highlight the cells A1:A4. Alternately,
simply enter the reference (=$A$1:$A$4).
6.
Make sure the In-Cell Dropdown option is checked. If you uncheck this
option, Excel still forces users to enter only list values (A1:A4), but it wont
present a drop-down list.
7.
Click OK.
You can add the drop-down list to multiple cells. Select the range of data input
cells (step 2) instead of a single cell. It even works for noncontiguous cells. Hold
down the Shift key while you click the appropriate cells.
Its worth noting that the drop-down arrow is visible only when the cell is active.
Automatically SUM () with Alt + =: Did you know you could add an
entire row or column by simply clicking the first empty cell? Click, press ALT
+ = and simply add up the numbers in every above cell.
Excel Tips & Tricks for a Successful and Efficient Data Analysis
Repeat the same formula for multiple cells: Typing the same formula
for all cells, No! First you need to create the formula in the first cell, and
then take the cursor to the right lower corner of the cell. See the cursor
turning into plus? Now simply double click to copy the formula and drag it
on the rest of cells in the column. Bingo, problem solved!
Copying a number or date pattern: This one is damn easy! Enter the
information in two rows to establish the pattern. Highlight those and drag
your cursor down to the number till which you want your cells to fill up
respectively. This will work with numbers, dates and months.
Double clicking format painter: With a simple mouse click, you can
now duplicate a format in other cells with only a click. Many excel users
use it by double clicking on the format painter to copy the format into
multiple cells. Yay!
worksheet as your data range. Sparklines can help you easily display trends in your
data in a compact format.
Also Read: 10 Simple Tips To Make Your Excel Charts Sexier
3. Manipulate Data with Pivot Tables
When you have a large, detailed data set, pivot tables allow you to easily manipulate
your data. These tables are interactive and can help you analyze data, detect patterns
and make comparisons. Creating a pivot table is as easy as using the built-in PivotTable
and PivotChart Wizard, located in the Data drop-down menu. The wizard helps you
choose the data to include in your PivotChart and format that information in a
meaningful manner. For more information on creating pivot tables, refer to
this PivotTable Tutorials.
4. Move Between Formulas and Results
To efficiently switch between the cell data and formula, use the Ctrl+tilde (~) keystroke.
This allows you to rapidly check formulas when working in a large spreadsheet.
5. Hide Zero Values
Hiding zero values can be helpful within large data sets by allowing you to see data
more clearly. To hide zero values, you simply need to change the options in your Excel
setup. Navigate to this function by clicking the File drop-down menu and choose
Options. Then choose Advanced from the left-hand menu and uncheck the box for
Show a zero in cells that have zero value. (Mac users: Go to the Excel drop-down
menu and choose Preferences, then uncheck Show zero values.)
But it turns out that theres a lot of data munging you can do in a plain old Excel
spreadsheet if you know how to craft the proper formulas.
In a presentation at the recent 2014 Computer Assisted Reporting (CAR) conference,
MaryJo Webster, senior data reporter with Digital First Media a newspaper group in
New York shared some of her favorite Excel tricks. The goal of these tips, Webster
said: Learn at least one new thing that will make you say, Why didnt I know this
before?
Date functions
Tip 1: Split dates into separate fields
You can extract the year, month and day into separate fields from a date field in Excel
by using formulas =Year(CellWithDate), =MONTH(CellWithDate) and
=DAY(CellWithDate). Splitting dates this way by year, month and day of month
works in Microsoft Access as well, Webster said.
In addition, you can also get the day of the week for any date in Excel with
=WEEKDAY(CellWithDate). The default returns numbers, not names of the days of
week, with 1 for Sunday, 2 for Monday and so on.
To display the name of the weekday instead of a number, apply a custom format to the
cells with the weekday numbers, using Format cells > Custom; then type ddd in the
Type text box to get three-day abbreviations or dddd for the full day name.
Tip 2: Find someones current age
If you have someones date of birth, you can find his or her current age on whatever
day you open the spreadsheet with the =DATEDIF() and =TODAY() functions. TODAY(),
as you might guess, gives the current date. DATEDIF() gives the difference between two
dates in units of years (y), months (m) or days (d), using the syntax:
=DATEDIF(Date1, Date2, Unit of measure)
So, to get current age in years, use the formula:
=DATEDIF(CellWithBirthday,TODAY(), y)
Note that the years unit returns ages in whole numbers and does not round up.
Reshaping data
Sometimes you need data in a format with one row for each observation, but what you already
have comes with multiple observations for each row instead. Heres one way to resolve it.
Tableau visualization software is one such tool that needs one data point per row, not
multiple data points per row, so the vendor created a Tableau Reshaper Tool that
works with recent versions of Excel on Windows.
You can download this free tool from the Tableau website. Although one add-in says
its for Excel 2010, it worked fine with Excel 2013 on my Windows 8 PC.
Several CAR attendees said theyve spent hours reshaping large data sets by manually
cutting and pasting, and the free Tableau tool will save them a lot of time. You dont
need to have other Tableau software installed on your system to use it.
The columns youre keeping as row ID columns should be placed on the left, and all
your data columns on the right. To use the reshaper tool, put your cursor on the first
cell with data that you want transformed. Then go to the Tableau menu and choose
reshape data. Say OK. You can watch a brief example below.
Its difficult to analyze a worksheet where column headers are interspersed with data, since you
cant easily sort, filter or visualize data by team. One way to deal with this is to add a new
column with, in this case, the team name for each player.
The trick is that you need to have a pattern to follow, according to Webster. In the
example above, the position column is empty for the team name rows but filled in for
the player rows. By filling in just the first cell with the team name manually, you can
then use this formula to automatically fill in the rest:
=IF(B3="",A3,C2)
That says: If cell B3 is blank, fill in the value of the cell in the first column of the same
row (in this case A3). Otherwise, fill in the value from the cell thats just above it (in this
case C2, which should be the team name from the row above for all the player rows).
Make sure to start with the first player row after having manually entered the first
header row.
still, what if someone else needs to work on your code and has to
figure out how it works?
This page discusses comments, code indentation and line breaks all
of which will assist in making your code clearer and easier to
interpret.
Comments
Don't worry if you don't understand some of the code in the example
above - this will be explained later in this tutorial. The example has
been included simply to show how comments are used to explain
each section of the code.
Code Indentation
Line Breaks
Your code can also be made more readable by inserting line breaks
in the middle of long lines of code. In VBA, if you want to split a line
up, you need to add a space followed by an underscore ( _) just
before the line break. This tells the VBA compiler that the current
line of code continues on the following line.
The following example shows how simple line breaks can be used to
make long lines of code much easier to read and understand.
Consider the following 'If' statement:
If (index = 1 And sColor1 = "red") Or (index = 2 And sColor1 =
"blue") Or (index
=
3 And sColor1
=
"green") Or (index
=
4 And sColor1 = "brown") Then
=
=
=
=
1
2
3
4
And
And
And
And
sColor1
sColor1
sColor1
sColor1
=
=
=
=
"red") Or _
"blue") Or _
"green") Or _
"brown") Then
When the 'If' statement is broken up over four lines, you can see the
different conditions within the 'If' statement much more clearly. This
example illustrates how presenting your code in a clear way can
help you to produce readable code, which will help you to avoid
introducing bugs or errors.
Data Types
All variables and constants have a data type. The following table
shows the VBA data types, along with a description of each type and
the range of possible values.
Data Type
Byte
Boolean
Integer
Long
Single
Double
Currency
Date
Object
String
Variant
From the above table, it is clear that you can save on memory by
using specific data types (e.g. Integers rather than Longs, or Singles
rather than Doubles). However, if you are planning to use the
'smaller' data types, you must be sure that your code will not
encounter larger values than can be handled by the data type.
Before using a variable or constant, you can declare it. This is done
by adding a simple line of code to your macro, as follows.
To declare a variable:
Dim Variable_Name As Data_Type
Note that in the above line of code, Variable_Name should be
replaced by your actual variable name and Data_Type should be
replaced by one of the above listed data types. For example:
Dim sVAT_Rate As
Single
Dim i As Integer
Constants are declared in a similar way, except a constant should
always be assigned a value when it is declared. Examples of the
declaration of constants in VBA are:
Const iMaxCount
5000
1.
3.
Option Explicit
The option 'Explicit' forces you to declare all variables that you use
in your VBA code, by highlighting any undeclared variables as errors
during compilation (before the code will run). To use this option,
simply type the line
Option Explicit
at the very top of your VBA file.
If you want to always include the option Explicit at the top of every
new VBA module that you open up, this can be done automatically
via the 'Require Variable Declaration' option of your VBA editor.
To do this:
Option Explicit
Dim sVAT_Rate As
Single
Function Total_Cost() As
Double
module).
.
.
.
End Function
Total_Cost function
and
then step
into
value
of
"sVAT_Rate"
will
be
remembered.
However, if you step into a function that resides
in a different module and attempt to use the
variable "sVAT_Rate", the variable will not be
recognised.
Option Explicit
Double
Dim sVAT_Rate As
Single
.
.
.
End Function
In the above example, the module level variable has been declared
using the 'Dim' keyword. However, it is possible that you may want
to declare variables that can be shared with other modules. This can
be specified by using the keyword Public in the declaration, instead
of 'Dim'.
Note that, for a module-level variable, the 'Dim' keyword could also
be replaced with the keyword Private to indicate that the scope of
the variable is limited to the current module.
Constants can also use the 'Public' and 'Private' keywords, but in this
case, the 'Public' or 'Private' keyword is used in addition to the
'Const' keyword (not instead of).
The following examples show the Public and Private keywords
applied to variables and constants:
Option Explicit
Public sVAT_Rate As
Single
declare
= 5000
the project.
the
variable,
"sVAT_Rate",
and
the
Option Explicit
Private sVAT_Rate As
Single
Private
Const iMax_Count =
5000
module,
but
can
not
be
accessed
from
Alternatively, you could use the much simpler and more organised
method of storing the Team members in an array of 20 String
variables:
Dim Team_Members(1 To 20) As String
Once you have declared the array as above, each entry of the array
is populated as follows:
Team_Members(1) = "John Smith"
.
.
.
You can declare arrays with 3 or more dimensions in the same way i.e. by adding further dimensions into the declaration and using a
further index to reference the array entries.
Dynamic Arrays
You then need to declare the dimension of the array during the
execution of the code, using the ReDim statement:
ReDim Team_Members(1 To 20)
If, during the execution of the code, you need to extend the size of
your array, you can useReDim again:
If Team_Size > 20 Then
Arguments
Optional Arguments
Sub AddToCells(ByVa
l i As Integer)
.
.
End Sub
Sub AddToCells(ByRe
f i As Integer)
When you exit the Sub, any changes that have been
.
End Sub
Function
.
.
.
End Function
The above very simple VBA Function procedure illustrates the way in
which data arguments are supplied to a procedure. It is also seen
that the Function procedure return type is defined as being a
'Double' (i.e. by the term "As Double" which is included after the
Function arguments).
The above example also shows how the Function procedure result is
stored in a variable that has the same name as the Function.
Sub main()
Dim total as Double
total = SumMinus(5, 4, 3)
End Sub
Sub
.
.
.
End Sub
VBA Sub Procedure Example 1: Center and Apply Font Size to a Selected
Range of Cells
VBA Sub Procedure Example 2: Center and Apply Bold Font to a Selected
Range of Cells
Sub Format_Centered_And_Bold()
Selection.HorizontalAlignment = xlCenter
Selection.VerticalAlignment = xlCenter
Selection.Font.Bold = True
End Sub
You can call a VBA Sub procedure from another VBA procedure by
typing the Call keyword, followed by the Sub name and then the Sub
procedure arguments enclosed in brackets. This is shown in the
example below:
Sub main()
Call Format_Centered_And_Sized( 20 )
End Sub
Sub main()
Call Format_Centered_And_Sized( arg1, arg2, ... )
End Sub
For those Sub procedures that are accessible from the workbook, a
simple way to run (or execute) the Sub is:
Press ALT-F8 (i.e. press the ALT key and while this is pressed
down, press F8);
From the list of macros select the macro you wish to run and
click the Run button.
Press ALT-F8 (i.e. press the ALT key and while this is pressed
down, press F8);
From the list of macros in the Macro dialog box, select the
macro you wish to assign a key combination to;
Public
Sub AddToCells(i
As Integer)
.
.
.
End Sub
Private
Sub AddToCells(i
As Integer)
.
.
End Sub
If you want to exit a VBA Function or Sub procedure before it has run
to the end, you can do this using the Exit Function or the Exit
Sub command. This is illustrated below, in a simple Function
procedure that expects to receive a positive value to work with. If
the value received is not positive, the function cannot continue, so it
highlights the error to the user and exits the procedure immediately:
the If ...
of these
If Condition1 Then
Actions if Condition1 evaluates to True
ElseIf Condition2 Then
Actions if Condition2 evaluates to True
Else
Actions if none of the previous conditions evaluate to True
End If
In the above If statement, the ElseIf and the Else parts of the
conditional statement can be left out if desired.
End If
In the above code block, the Case Else part of the conditional
statement is optional.
In the example below, the Select Case statement is used to color the
current active cell, depending on the value of the cell contents.
End Select
Case 6, 7,
8, 9
Case 10
Case Else
The Visual Basic 'For' loop takes on two separate forms. These are
the For ... Next loop and the For Each loop.
The For ... Next Loop
The For ... Next loop uses a variable, which is set to a series of
values within a specified range. The VBA code inside the loop is then
executed for each value. This is best explained by way of a simple
example:
For i = 1 To 10
Total = Total + iArray(i)
Next i
The above simple For ... Next loop sets the variable i to have the
values 1, 2, 3, ..., 10, and for each of these values, runs through the
VBA code inside the loop. Therefore, in the above example, the loop
adds each of the members of the array 'iArray' to the variable,
'Total'.
In the above example, no step size is specified, so the loop uses the
default step size of 1, when looping from 1 to 10. However, you may
sometimes want to step through a loop using different sized steps.
This can be done using the Step keyword, as shown in the following
simple example.
Next d
In the above For loop, because the step size is specified as 0.1, the
value of the variable d is set to the values 0.0, 0.1, 0.2, 0.3, ..., 9.9,
10.0 for each execution of the VBA code inside the loop.
You can also use negative step sizes in the VBA For loop, as is
illustrated below:
For i = 10 To 1 Step -1
iArray(i) = i
Next i
In this example, the step size is specified as -1, and so the loop sets
the variable, i, to have the values, 10, 9, 8, ..., 1.
The For Each loop is similar to the For ... Next loop but, instead of
running through a set of values for a variable, the For Each loop runs
through every object within a set of objects. For example, the
following code shows the For Each loop used to list every Worksheet
in the current Excel Workbook:
If, you want to exit a 'For' Loop early, you can use the Exit
For statement. This statement causes VBA to jump out of the loop
and continue with the next line of code outside of the loop. For
example, you may be searching for a particular value in an array.
You could do this by looping through each entry of the array, but
when you find the value you are looking for, you no longer wish to
continue searching, so you exit the loop early.
The Exit For statement is illustrated in the following example, which
loops through 100 array entries, comparing each to the value 'dVal'.
The loop is exited early if dVal is found in the array:
For i = 1 To 100
If dValues(i) = dVal Then
indexVal = i
Exit For
End If
Next i
' Sub procedure to list the Fibonacci series for all values below 1,000
Sub Fibonacci()
Dim i As Integer ' counter for the position in the series
Dim iFib As Integer ' stores the current value in the series
Dim iFib_Next As Integer ' stores the next value in the series
Dim iStep As Integer ' stores the next step size
' Initialise the variables i and iFib_Next
i=1
iFib_Next = 0
' Do While loop to be executed as long as the value of the
' current Fibonacci number exceeds 1000
Do While iFib_Next < 1000
If i = 1 Then
' Special case for the first entry of the series
iStep = 1
iFib = 0
Else
' Store the next step size, before overwriting the
It can be seen that, in the above example, the condition iFib_Next <
1000 is tested at the start of the loop. Therefore, if the first value of
iFib_Next were greater than 1,000, the loop would not be executed
at all.
Another way that you can implement the Do While loop is to place
the condition at the end of the loop instead of at the beginning. This
causes the loop to be executed at least once, regardless of whether
or not the condition initially evaluates to True.
The following code shows the form of a Do While Loop which has the
condition at the end of the loop:
Do
.
.
.
Loop While iFib_Next < 1000
The Do Until loop is very similar to the Do While loop. The loop
repeatedly executes a section of code until a specified condition
evaluates to True. This is shown in the following sub procedure,
where a Do Until loop is used to extract the values from all cells in
Column A of a Worksheet, until it encounters an empty cell :
iRow = 1
Do Until IsEmpty(Cells(iRow, 1))
' Store the current cell value in the dCellValues array
dCellValues(iRow) = Cells(iRow, 1).Value
iRow = iRow + 1
Loop
Do
.
.
.
Loop Until IsEmpty(Cells(iRow, 1))
Mathematical Operators
The main Mathematical VBA operators are listed in the table below.
The precedences that are listed alongside the operators are the
defaults, which are applied in the absence of brackets. However, the
order in which the VBA operators are applied can be controlled by
adding brackets to an expression:
Operator
^
*
/
\
Mod
+
-
String Operators
Operator
&
Oper
<
<
>
<
>
It should be noted that the above tables are not an exhaustive list of
VBA operators. A more complete list can be obtained from the Visual
Basic Developer Center Website
Built-In Functions
VBA also has a large number of built-in functions that are available
to be used in your VBA code. Some of the more commonly used VBA
functions are listed below.
Functio
n
Action
Abs
Chr
Date
DateAd
d
the
format DateAdd(Interval,
Represents
yyyy
year
quarter
e.g.
month
day
weekday
ww
week
hour
minute
second
DateDi
f
DateDif("w", "01/01/2015",
"03/03/2016")calculates the number of weeks between
the dates "01/01/2015" and "03/03/2016", and so
returns the value 61.
Day
Hour
InStr
Int
IsDate
IsError
IsMissi
ng
IsNum
eric
Left
Len
Month
Mid
E.g.
Time
UBoun
d
Year
Description
Applicati
on
Workboo
ks
Workboo
k
Sheets
Workshe
ets
Workshe
et
Sheets("Sheet1") or Worksheets("Wksheet1")).
You can also use 'ActiveSheet' to access the
current active Sheet.
From the Worksheet object, you can access the
Rows and Columns objects, which are collections
of Range objects relating to the Rows and
Columns of the Worksheet. You can also access
an individual cell or any Range of contiguous
cells on the Worksheet.
Rows
Columns
Range
The above table describes how you access Excel objects via 'parent'
objects. For example, a range of cells may be referenced by the
expression:
Workbooks("WB1").Worksheets("WS1").Range("A1:B10")
Another point to note, when working with Excel objects is that, when
an object is being assigned to a variable in your vba code, you must
use the Set keyword as follows:
Dim DataWb As Workbook
Set DataWb = Workbooks("Data.xlsx")
At any one time, Excel will have an Active Workbook, which is the
workbook that is currently selected. Similarly, there will be
an Active Worksheet and an Active Range, etc.
The current active Workbook or Sheet can be referred to, in your vba
code asActiveWorkbook, or ActiveSheet, and the current active
range can be accessed by referring toSelection.
If, in your VBA code, you refer to a worksheet, without referring to a
specific workbook, Excel defaults to the current Active Workbook.
Similarly, if you refer to a range, without referring to a specific
workbook or worksheet, Excel defaults to the current Active
Worksheet in the current Active Workbook.
Therefore, if you wish to refer to range A1:B10 on the current Active
Worksheet, within the current Active Workbook, you can simply type:
Range("A1:B10")
Changing the Current Active Object
If, during the execution of your code, you wish to change the current
Active Workbook, Worksheet, Range, etc, this can be done using the
'Activate' or 'Select' methods as follows:
Workbooks("Book1.xlsm").Activate
Worksheets("Data").Select
Range("A1", "B10").Select
Object Methods such as the 'Activate' and 'Select' methods used
above, are discussed in more detail below.
Object Properties
Object Methods
VBA objects also have methods that perform specific actions. Object
methods are procedures that are associated to a specific object
type. For example, the Workbook object has the methods 'Activate',
'Close', 'Save', and many more.
An Object Method can be called by referring to the object name
followed a dot and then the method name. For example, the current
active Workbook can be saved using the code:
ActiveWorkbook.Save
Like any other procedures, methods can have arguments that are
supplied when the method is called. For example, the Workbook
'Close' method has three optional arguments which are used to
provide information to the method such whether the Workbook is to
be saved before closing, etc.
The method arguments are supplied to the method by following the
call to the method with the argument values, separated by commas.
For example, if you wanted to save the current active workbook as a
.csv file called "Book2", you would call the Workbook SaveAs
method with the Filename argument set to "Book2" and the
FileFormat argument set to xlCSV:
ActiveWorkbook.SaveAs "Book2", xlCSV
To make your code more readable, you can use named arguments
when calling a method. In this case, you type the argument name
followed by the assignment operator := and then the value.
Therefore, the above call to the Workbook SaveAs method could be
written as:
ActiveWorkbook.SaveAs Filename:="Book2", [FileFormat]:=xlCSV
Examples
Example 1
The following VBA code snippet was previously used to illustrate the
use of the For Each loop. It is now useful to re-visit this code to
examine the references to the Worksheets object (taken from the
current active Workbook by default), and the reference to each
individual Worksheet. Note that the Worksheet Name property is
accessed, to display the name of each Worksheet.
Example 2
' Copy a range of cells from Sheet1 of another Workbook (named "Data.xlsx"),
' and paste the values into the "Results" Worksheet of the current Workbook
' (named "CurrWb.xlsm")
Dim dataWb As Workbook
Set DataWb = Workbooks.Open("C:\Data")
' Note that DataWb is the current Active Workbook.
' Therefore the following accesses the 'Sheets' Object in DataWb.
Sheets("Sheet1").Range("A1:B10").Copy
' Paste the values from the copied Range into the "Results" Worksheet of
' the current Workbook. Note that, as CurrWb is not the current Active
' Workbook, we need to specify this Workbook.
Workbooks("CurrWb").Sheets("Results").Range("A1").PasteSpecial
Paste:=xlPasteValues
Example 3
also seen that, when a cell or cell range on the current active
Worksheet is accessed, the reference to the Worksheet can be
omitted. Again the code provides an illustration of the use of
the Set keyword to assign a Range object to the variable 'Col'.
The code also includes an example of how to access and change the
Range object's Value property.
Loop
The term 'Excel Events' refers to specific actions that a user carries
out in Excel. For example, if the user selects a Worksheet, this is an
event. Similarly, entering data into a cell or saving a Workbook are
also Excel events.
Events are linked to Excel Worksheets, Charts, Workbooks, or to the
Excel Application itself. This enables the programmer to create vba
code to be executed automatically at the time of an event.
For example, if you wanted to run a macro every time a user
selected any Worksheet in the Workbook, this could be done by
writing vba code that is linked to the Workbook event
"SheetActivate".
Alternatively, if you wanted to run a macro every time
a specific Worksheet (e.g. "Sheet1") was selected, you would link
your code to the Worksheet event "Activate" for Sheet1.
How to Link Code to a Specific Event
1.
Open up the VBA Editor (by pressing ALT-F11) and open up the
code window for the object relating to the event that you are
interested in linking code to. For example, if you want to execute a
section of code every time a specific worksheet event occurs, you
should open up the code window for that worksheet. This is shown in
the image below:
2.
3.
feeds into that function (if there are any) are included into the Sub
header - you then just need to add the vba code to define what you
want to do when that event is fired.
Example
The following example displays a message box every time the cell
B1 in the Worksheet "Sheet1" is selected.
For this action, we need to use the Worksheet Event
"Selection_Change", which 'fires' every time a different cell or range
of cells is selected. The "Selection_Change" function receives, as an
argument, a Range object called "Target". This tells you the range of
cells that has been selected.
As the "Selection_Change" event relates to any new selection, we
need to check the supplied Range, 'Target', as soon as the function
is called, to make sure that the required actions are performed, only
when cell B1 is selected. The code for this is shown below:
There are three types of VBA error that you may encounter when
executing an Excel macro. These are:
Compile Errors;
Runtime Errors;
Logical Errors ('bugs').
Compile Errors
the error in red, depending on the setting of the Auto Syntax Check
option (see right).
Alternatively, a compile error may be detected when the code is
compiled, just before being executed.
Runtime Errors
Runtime errors occur during the execution of your code, and cause
the code to stop running. This type of VBA error is also relatively
easy to fix, as you will be given details of the nature of the error,
and shown the location where the code has stopped running.
For example, if your code attempts to divide by zero, you will be
presented with a message box, which states"Run-time error '11':
Division by zero".
Depending on the structure of your VBA project, you may be given
the option to debug the code, (see below). In this case, clicking on
the Debug button on the debug message box, causes the line of
code that generated the VBA error to be highlighted in your vba
editor.
Due to the message box content and the highlighted line of code in
the above example, it is very easy to spot the error in this code.
If your code is more complex, you can gain further information on
the reason for the VBA error by looking at the values of the variables
in use. This can be done in the VBA editor by simply hovering your
mouse cursor over the variable name, or by opening the local
variables window (by selecting ViewLocals Window).
Out of memory
1
1
1
3
Division by zero
Type mismatch
(this error arises when you attempt to
assign the wrong type of value to a
variable - e.g. define i as an integer,
then attempt to assign the string "text"
to i)
5
3
' Sub procedure to set the supplied values, Val1 and Val2 to the values
' in cells A1 and B1 of the Workbook "Data.xls" in the C:\ directory
Sub Set_Values(Val1 As Double, Val2 As Double)
Dim DataWorkbook As Workbook
On Error GoTo ErrorHandling
In the code above, the code attempts to open the Excel File 'Data'
and if it fails to find the file, prompts the user to place the data file
into the correct folder. Once the user does this and clicks OK, the
code is resumed and a further attempt is made to open the file. If
desired, instead of re-trying the file, the Sub procedure could be
terminated at this point, by using theExit Sub command.
Logical Errors
Steve would like to create an IF statement (using the worksheet function) based on the color of a
cell. For example, if A1 has a green fill, he wants to return the word "go", if it has a red fill, he
wants to return the word "stop", and if it is any other color return the word "neither". Steve
prefers to not use a macro to do this.
Unfortunately, there is no way to acceptably accomplish this task without using macros, in one
form or another. The closest non-macro solution is to create a name that determines colors, in
this manner:
2. Click Insert | Name | Define. Excel displays the Define Name dialog
box.
3. Use a name such as "mycolor" (without the quote marks).
4. In the Refers To box, enter the following, as a single line:
=IF(GET.CELL(38,Sheet1!A1)=10,"GO",IF(GET.CELL(38,Sheet1!A1)
=3,"Stop","Neither"))
5. Click OK.
With this name defined, you can, in any cell, enter the following:
=mycolor
The result is that you will see text based upon the color of the cell in which you place this
formula. The drawback to this approach, of course, is that it doesn't allow you to reference cells
other than the one in which the formula is placed.
The solution, then, is to use a user-defined function, which is (by definition) a macro. The macro
can check the color with which a cell is filled and then return a value. For instance, the following
example returns one of the three words, based on the color in a target cell:
Function CheckColor1(range)
If range.Interior.Color = RGB(256, 0, 0) Then
CheckColor1 = "Stop"
ElseIf range.Interior.Color = RGB(0, 256, 0) Then
CheckColor1 = "Go"
Else
CheckColor1 = "Neither"
End If
End Function
This macro evaluates the RGB values of the colors in a cell, and returns a string based on those
values. You could use the function in a cell in this manner:
=CheckColor1(B5)
If you prefer to check index colors instead of RGB colors, then the following variation will work:
Function CheckColor2(range)
If range.Interior.ColorIndex = 3 Then
CheckColor2 = "Stop"
ElseIf range.Interior.ColorIndex = 4 Then
CheckColor2 = "Go"
Else
CheckColor2 = "Neither"
End If
End Function
Whether you are using the RGB approach or the color index approach, you'll want to check to
make sure that the values used in the macros reflect the actual values used for the colors in the
cells you are testing. In other words, Excel allows you to use different shades of green and red,
so you'll want to make sure that the RGB values and color index values used in the macros
match those used by the color shades in your cells.
One way you can do this is to use a very simple macro that does nothing but return a color index
value:
=GetFillColor(B5)
The result is the color index value of cell B5 is displayed. Assuming that cell B5 is formatted
using one of the colors you expect (red or green), you can plug the index value back into the
earlier macros to get the desired results. You could simply skip that step, however, and rely on
the value returned by GetFillColor to put together an IF formula, in this manner:
http://www.cpearson.com/excel/colors.aspx
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (10780)
applies to Microsoft Excel 2007 and 2010. You can find a version of this tip for the
older menu interface of Excel here: Colors in an IF Function.
Related Tips:
Converting to Octal
Comprehensive VBA Guide Visual Basic for Applications (VBA) is the language used for writing
macros in all Office programs. This complete guide shows both professionals and novices how to
master VBA in order to customize the entire Office suite for their needs.