DAS Practicals VBA Notes
DAS Practicals VBA Notes
Let us review
Ex06MaturityDateCalc
Types of Names :
Defined name A name that represents a cell, range of cells, formula, or constant value.
Table name A name for an Excel table, which is a collection of data about a particular subject that is stored in records
(rows) and fields (columns).
The V in VLOOKUP stands for vertical. Use VLOOKUP instead of HLOOKUP when your comparison
values are located in a column to the left of the data that you want to find.
Syntax
VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
Lookup_value The value to search in the first column of the table array (array: Used to build single formulas
that produce multiple results or that operate on a group of arguments that are arranged in rows and columns.
An array range shares a common formula; an array constant is a group of constants used as an
argument.). Lookup_value can be a value or a reference. If lookup_value is smaller than the smallest
value in the first column of table_array, VLOOKUP returns the #N/A error value.
Table_array Two or more columns of data. Use a reference to a range or a range name. The values in the
first column of table_array are the values searched by lookup_value. These values can be text, numbers,
or logical values. Uppercase and lowercase text are equivalent.
Col_index_num The column number in table_array from which the matching value must be returned. A
col_index_num of 1 returns the value in the first column in table_array; a col_index_num of 2 returns
the value in the second column in table_array, and so on. If col_index_num is:
Less than 1, VLOOKUP returns the #VALUE! error value.
Greater than the number of columns in table_array, VLOOKUP returns the #REF! error value.
***
http://www.experiglot.com/2007/12/27/how-to-use-vlookup-in-excel-part-ii-
some-tips-and-advanced-excel-tricks/
Microsoft Excel data validation lets you define what type of data you
want entered in a cell. For example, you can allow entry of a letter grade
with only the letters A through F. You can set up data validation to
prevent users from entering data that isn't valid, or allow invalid data
but check for it after the user is finished. You can also provide messages
to define what input you expect for the cell, and instructions to help
users correct any errors.
Data validation is particularly useful when you're designing forms or
worksheets that other people will use to enter data, such as budget
forms or expense reports.
The first step in creating a Pivot Table is to organize your data in a list of rows
and columns. In Excel 2007, you can format this list as an Excel Table, and use
that as the dynamic source for your Pivot Table.
Before you create a pivot table, make sure your data is organized correctly.
There are instructions on the following pages, for setting up your source data in
a table, organized into rows and columns.
An empty pivot table is created in your workbook, either on a new sheet, or the
existing sheet that you selected. When you select a cell within the pivot table,
a PivotTable Field List appears, at the right of the worksheet.
In a Pivot Table, you can group the items in a Row or Column field.
For example, items in a date field can be grouped by month, and items
in a number field can be grouped by tens.
In the Sample Pivot Sales book -> TestPivot sheet
Right-click the Date field button.
Choose Group to select the Group Field
Sort and Filter Sorting and Filtering allow you to manipulate data in
a worksheet based on given set of criteria.
Basic Sorts To execute a basic descending or ascending sort based on
one column:
1. Highlight the cells that will be sorted
2. Click the Sort & Filter button on the Home tab
3. Click the Sort Ascending (A-Z) button or Sort Descending (Z-
A) button
Open Ex10PivotSales.xlsx
Let us review Ex10PivotTableExpensesByWeekCategory.xls
Verify the results using Sort & Filter
Let us review Ex11SortFilter example
Formulas are one of the most useful and well used features in spreadsheets such as Excel.
Formulas can be used to perform basic number crunching, such as addition or subtraction,
well as more complex calculations such as payroll deductions or averaging a student's test
results. Using formulas effectively is central to getting the most out of your spreadsheets.
ADDITION cell A1 to A10 = sum (A1: A10)
AVERAGE cell A1 to A10 = average (A1: A10)
MAXIMUM cell A1 to A10 = max (A1: A10)
MINIMUM cell A1 to A10 = min (A1: A10)
IF(A1 <= 0; "ordering", "stock")
• This would mean: If the contents of cell A1 is less than or equal to zero, then it displays "to order", otherwise (if the content
of cell A1 is greater than zero) on display "at stock".
Switch between displaying formulas and their values on a worksheet
• Press CTRL + ` (grave accent).
Financial Functions
Let us review
Ex09PMTFinanCalc
IF function
The IF function is one of the most popular functions in Excel, and it
allows you to make logical comparisons between a value and what
you expect. In its simplest form, the IF function says:
IF(Something is True, then do something, otherwise do something
else)
So an Simple IF statement can have two results. The first result is if
your comparison is True, the second if your comparison is False.
IF statements are incredibly robust, and form the basis of many
spreadsheet models, but they are also the root cause of many
spreadsheet issues. Ideally, an IF statement should apply to minimal
conditions, such as Male/Female, Yes/No/Maybe, to name a few, but
sometimes you might need to evaluate more complex scenarios that
require nesting* more than 3 IF functions together.
Let us review
Ex12IFFunction
• An Excel Web query allows you to bring data from a Web site i
an Excel worksheet. It will find any tables on the Web page and le
you select the ones containing data you want to put into your
worksheet, allowing for dynamic updates from the Web page. We
queries are not just useful for pulling information from standard
HTML pages. They can also be used quite nicely in situations whe
standard ODBC connection would be difficult or impossible to cre
or maintain try: http://finance.yahoo.com/q?s=EURUSD=X
Let us review
Ex09DBAccessExportedSupplier
Charts can convey much more than numbers alone can because
charts present data in a visual way that makes it easier to see the
meaning behind the numbers. And with the new charting
capabilities in Microsoft Office, it's easier than ever to turn raw da
into meaningful information.
Charts start with data. In Office Excel, you just select data in your
worksheet, choose a chart type that best suits your purpose, and
click. Want to try a different chart type? Just click again and selec
new chart type from a huge range of possibilities. Then work with
the new Chart Tools to customize the design, layout, and formatti
Novemberof
09 your chart. You MS
can
Excelsee howMath
2007 - Rajesh various34options would look just by
Reporting: Charts
1. The chart area (chart area: The entire chart and all its elements.) of the chart.
2.The plot area (plot area: In a 2-D chart, the area bounded by the axes, including all data series. In a 3-D chart, the area bounded by the axes,
including the data series, category names, tick-mark labels, and axis titles.) of the chart.
3.The data points (data points: Individual values plotted in a chart and represented by bars, columns, lines, pie or doughnut slices, dots, and various
other shapes called data markers. Data markers of the same color constitute a data series.) of the data series (data series: Related data points that are
plotted in a chart. Each data series in a chart has a unique color or pattern and is represented in the chart legend. You can plot one or more data series
in a chart. Pie charts have only one data series.) that are plotted in the chart.
4.The horizontal (category) and vertical (value) axis (axis: A line bordering the chart plot area used as a frame of reference for measurement. The y
axis is usually the vertical axis and contains data. The x-axis is usually the horizontal axis and contains categories.) along which the data is plotted in
the chart.
4.The legend (legend: A box that identifies the patterns or colors that are assigned to the data series or categories in a chart.) of the chart.
6. A chart and axis title (titles in charts: Descriptive text that is automatically aligned to an axis or centered at the top of a chart.) that you can use in
the chart.
7.A data label (data label: A label that provides additional information about a data marker, which represents a single data point or value that
originates from a datasheet cell.) that you can use to identify the details of a data point in a data series.
After you create a chart, you can modify any one of its elements. For example, you might want to change the way that axes
are displayed, add a chart title, move or hide the legend, or display additional chart elements.
To modify a chart, you can:
Change the display of chart axes You can specify the scale of axes and adjust the interval between the values or categories that are
displayed. To make your chart easier to read, you can also add tick marks (tick marks and tick-mark labels: Tick marks are small
lines of measurement, similar to divisions on a ruler, that intersect an axis. Tick-mark labels identify the categories, values, or series
in the chart.) to an axis, and specify the interval at which they will appear.
Add titles and data labels to a chart To help clarify the information that appears in your chart, you can add a chart title, axis
titles, and data labels.
Add a legend or data table You can show or hide a legend, change its location, or modify the legend entries. In some charts, you can
also show a data table (data table: A range of cells that shows the results of substituting different values in one or more formulas.
There are two types of data tables: one-input tables and two-input tables.) that displays the legend keys (legend keys: Symbols in
legends that show the patterns and colors assigned to the data series (or categories) in a chart. Legend keys appear to the left of
legend entries.
Formatting a legend key also formats the data marker that's associated with it.) and the values that are presented in the chart.
Apply special options for each chart type Special lines (such as high-low lines and trendlines (trendline: A graphic representation of
trends in data series, such as a line sloping upward to represent increased sales over a period of months. Trendlines are used for the
study of problems of prediction, also called regression analysis.)), bars (such as up-down bars and error bars), data markers (data
marker: A bar, area, dot, slice, or other symbol in a chart that represents a single data point or value that originates from a worksheet
cell. Related
November 09 data markers in a chart constitute a dataMS series.),
Excel and2007
other options
- Rajeshare available
Math for different37 chart types.
Reporting: Dashboards
A dashboard is a visual display of the most important information […] which fits entirely
on a single computer screen
Excel Dashboards are a front end for your data so that, instead of looking at all your data,
you look at the subset of the data that you are most interested in. In an enterprise
environment dashboards are often created by technical specialists and provided to users so
they can see just the data that they need to work with. However, some techniques
employed in creating a dashboard are simple enough that you can use them to analyze and
display your own data.
The most significant improvements in Excel fall in the area of data visualization. In the
new release, a colored gradient in cell backgrounds can be used to represent a cell’s value.
The higher the value, the longer the bar. Excel 12 gives you the ability to create your own
dashboards. Traditionally, the three-color traffic light (red, yellow, green) has been a
popular way for end users to spot problems. Now traffic lights—and a variety of other
graphics, such as arrows—are available in Excel 12, and you can define the intervals each
colored light is assigned.
Your dashboard can also display Key Performance Indicators (KPIs) to measure the
progress that your organization is making toward its goals
38
Dashboard:The implementation
First have our raw data ready in a separate sheet, this is the easy step, you know how to get your data in to one sheet.
Next create a 10 row table for the dash board
Insert a scroll bar form control Go to Menu > view > tool bars and select “forms” to see the forms tool bar. Select the
scrollbar control from forms tool bar and draw one on your spreadsheet.
Assign the scroll bar control to a cell right click on it and select format control option. In the dialog box, go to “control”
tab and adjust the values as shown below.
Finally write OFFSET() formula to display any consecutive 10 values in our scrollable table: OFFSET is used on the
dashboard to bring back those 10 lines from the sheet with the raw data that are selected by using the scroll bar. A sample
formula is shown here: =OFFSET(Data!E5,Calculation!$D$5,0) where Data!E5 refers to the column containing the
required data, Calculation!$d$5 has the current scroll bar value. That is all, you will have a small table that you can use to
see all data using scroll
It allows users to input data into cells included in a grid made of rows
and columns. The user can introduce functions and, referring to the cells
by its name (formed by the letter or combinations of letters that
identifies the column and the number that identifies the row), can
display the result in that cell. The result will change dynamically if the
content of the included cells changes.
If you perform a task repeatedly in Microsoft Excel, you can automate the
task with a macro. A macro is a series of commands and functions (function:
A prewritten formula that takes a value or values, performs an operation,
and returns a value or values. Use functions to simplify and shorten formulas
on a worksheet, especially those that perform lengthy or complex
calculations).
Complex macros are usually created in Excel with the Macro editor.
Simpler macros can, however, be created using the Excel macro
recorder.
VBA newcomers are often overwhelmed by the terminology that is used in VBA. I’ve put together some key
definitions to help you keep the terms straight. These terms cover VBA and UserForms two important elements
that are used to customize Excel.
1. Code: VBA instructions that are produced in a module sheet when you record a macro. You also can enter VBA
code manually.
2. Controls: Objects on a UserForm (or in a worksheet) that you manipulate. Examples include buttons, check
boxes, and list boxes.
3. Function: One of two types of VBA macros that you can create. (The other is a Sub procedure.) A function
returns a single value. You can use VBA functions in other VBA macros or in your worksheets.
4. Macro: A set of VBA instructions performed automatically.
5. Method: An action taken on an object. For example, applying the Clear method to a Range object erases the
contents and formatting of the cells.
6. Module: A container for VBA code.
7. Object: An element that you manipulate with VBA. Examples include ranges, charts, drawing objects, and
8. so on.
9. Procedure: Another name for a macro. A VBA procedure can be a Sub procedure or a Function procedure.
Property: A particular aspect of an object. For example, a Range object has properties, such as Height, Style, and
Name.
10. Sub procedure: One of two types of Visual Basic macros that you can create. The other is a function.
11. UserForm: A container that holds controls for a custom dialog box and holds VBA code to manipulate the
controls.
12. VBA: Visual Basic for Applications. The macro language that is available in Excel, as well as in the other
applications in Microsoft Office.
13. VB Editor: The window (separate from Excel) that you use to create VBA macros and UserForms.
December 16 MS Excel 2007 Manager - Rajesh Math 44
Excel Macros : VBA
You will develop, test and modify VBA procedures (macros) in the Excel Visual Basic
Editor (VBE). It is a very user friendly development environment. The VBA procedures
developed in the Excel Visual Basic Editor become part of the workbook in which they are
developed and when the workbook is saved the VBA components (macros, modules, user
forms. etc.) are saved at the same time. When you send the workbook to the "Recycling bin"
the VBA procedures are gone.
The immediate window is used when you are developing your macro code
If you store one or more macros in a workbook, the file must be saved with macros
enabled, which is a file with an XLSM extension.
A VBA macro (also known as a procedure) can be one of two types:
1. Sub : It is a new command that either the user or another macro can execute.
2. Function : A function always returns a single value (just as a
worksheet function always returns a single value).
A VBA module, which is displayed in a separate window, works like a text editor. You can
move through the sheet, select text, insert, copy, cut, paste, and so on.
You perform actions in VBA by writing (or recording) code in a VBA module sheet and
then executing the macro in any one of various ways. VBA modules are stored in an Excel
workbook, and a workbook can hold any number of VBA modules.
When you enter code in a module sheet, you’re free to use indenting and blank lines to
make the code more readable. (In fact, this is an excellent habit.)
After you enter a line of code (by pressing Enter), it’s evaluated for syntax errors. If none
are found, the line of code is reformatted, and colors are added to keywords and identifiers.
Most user-created macros are designed for use in a specific workbook, but you may want
to use some macros in all your work. You can store these general-purpose macros in the
Personal Macro Workbook so that they’re always available to you. The Personal Macro
Workbook is loaded whenever you start Excel.
The Dim (stands for dimension) statement is used to declare variables and allocate storage space. It
may appear in a General Declarations section at the top of a code module -or- immediately following
a procedure declaration.
For example ...
Sub SampleCode()
Dim
MyNumber
as Integer
' Other program statements go here
End Sub
Variables declared within a procedure are not available to other procedures and they only retain values
for the life of that procedure. This refers to a variable's scope. Variables declared at a module-level (or
within a form's General Declarations section) are available to all procedures within that module or
form
-and- they continue to retain assigned values for the life of the program. However, these variables are
not available to procedures outside of the module in which they are declared. One alternative to the
Dim statement is the Public keyword, which expands the scope of the variable to make it available to
other procedures outside it's own module or form. It's a better practice to use the narrowest possible
scope for your variables.
Note: Other approaches to scope involve Global, Private, and Static declaration. Also, very
similar to variables are Constants.
December 16 MS Excel 2007 Manager - Rajesh Math 51
Data Type(s)
End Sub
The Select Case statement executes one of several statements based on the
value of an expression
Msgbox : Displays a message in a dialog box, waits for the user to click
a button, and returns an Integer indicating which button the user
clicked.
Syntax
MsgBox(prompt[, buttons] [, title] [, helpfile, context])
Displays a prompt in a dialog box, waits for the user to input text or
click a button, and returns a String containing the contents of the text
box.
Syntax
InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])
Loops
1. Do Loop : Suppose you wanted to count the number of rows in a
range of data that can sometimes be small and sometimes really big.
You'd want to use a Do…Loop. This type of loop performs an
action as many times as necessary. It would count whatever number
of rows it found in the range.
Here the While condition is used so that the loop runs as long as
the cell being acted on is not blank. The row being worked on is x,
and (x,1) is the first cell in that row. Used together, the signs <>
mean "does not equal." The quotation marks with nothing between
them indicate a blank cell.
If you wanted the loo
Loops
2. The For Each…Next Loop : You would use the For Each…Next
loop to perform an action on every cell in a range of data.
Suppose, for example, that you wanted to make the word "OK"
darker than other text everywhere in a selected range .
"MyCell" means whatever cell the loop is working on, and "For
Each" means that the loop will work on all cells in the selection. If
the loop finds a cell containing only the word "OK", then it makes
that word darker.
Loops
3. The Do…Loop and the For Each…Next loop are powerful in
simple ways. Now we're going to ratchet up the complexity a bit
by introducing nested loops. You use nested loops when you need
to perform an action on a range of data more than once, or through
more than one range of data. For an analogy to nested loops, think
of the Earth revolving around the Sun. One full revolution around
the Sun, a year, is like the outside loop, and one rotation of the
Earth around its axis, a day, is like the inside loop nested within
the outside loop. For each year, there are 365 inside loops, and on
every January 1st, the outside loop repeats.
December 16:
MS VerExcel
1.0 2007 Manager - Rajesh Math 66
Programming Charts
Option Explicit
Private Sub Worksheet_Activate()
'Select the data source
Range("A1:G2").Select
'Create a clusted column chart
ActiveSheet.Shapes.AddChart , 10, 100
ActiveSheet.Shapes(1).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$G$2"), PlotBy:=xlRows
'Specify Pie chart type
ActiveChart.ChartType = xl3DPie
The total of all data points from all categories represents 100% of the chart. To add a pie
chart to the Excel sheet, you can use the ChartType property of the current active
chart(ActiveChart.ChartType=xl3DPie).
December 16:
MS VerExcel
1.0 2007 Manager - Rajesh Math 67
QUESTIONS ?