ADVANCE INFORMATION TECHNOLOGY TRAINING PROGRAMME
COURSE MATERIAL MODULE – I
Board of Studies
The Institute of Chartered Accountants of India, New Delhi
The objective of this background material is to provide uniform reference material to the students undergoing 100 hours Advanced Information Technology Training. All attempts have been made to make the discussion simple and comprehensive. Students may note that the material has been prepared with an objective to help them in acquiring requisite knowledge and skills in the subject and gain hands on experience. This is also expected to serve as a source of reference book in their future education and training. In case students have any suggestions to make for further improvement of the material contained herein, they may write to Board of Studies or ITT Section, IT Directorate, ICAI Bhawan, A-29, Sector – 62, Noida. Queries can also be sent to :
[email protected]. All care has been taken to provide the material in a manner useful to the students. However the material has not been specifically discussed by the Council of the Institute or any of its Committees and the views expressed herein may not be taken to necessarily represent the views of the Council or any of its Committees. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted, in any forms or by any means, electronic, mechanical, photocopying, recording or otherwise, without prior permission, in writing, from the Institute.
©The Institute of Chartered Accountants of India
Revised Edition :
November, 2013
ISBN : 978-81- 8441-
Published by The Publication Department on behalf of The Institute of Chartered Accountants of India, ICAI Bhawan, Post Box No. 7100, Indraprastha Marg, New Delhi- 110 002, India.
Printed at Repro India Limited, 50/2, TTC MIDC Industrial Area, Mahape, Navi Mumbai 400 710, India. September / 2014 / 30,000 Copies (Revised)
A WORD ABOUT “Course Material on Advanced Information Technology Training” The impact of Information Technology (IT) on several aspects of accounting profession and practice has been pronounced over the last two decades. The revolutionary developments of various IT tools and techniques have a far reaching impact on the organizations. In today’s business world, accounting professionals have to interact with computer-based Information systems on a regular basis. As primary users of information systems in organizations, accountants need to participate in the design, development and operations of IT systems. Accountants today need to measure and evaluate the performance of information systems. Internal and external auditors must assess the quality of information systems and evaluate the accuracy of information input and output. The Institute of Chartered Accountants of India has been making earnest efforts to develop a contemporary body of knowledge and skill set for its students by updating its curriculum from time to time. Considering the importance of IT, ICAI has introduced Advanced course on Information technology for students undergoing third year of practical training. In order to impart synchronized and uniform theoretical and practical knowledge to all the aspiring CA students in the IT area,the Institute has established its own IT labs equipped with computers of latest configuration,software and other infrastructural facilities at almost all its branches and regional offices. It is desired that a student should undergo 100 Hours of Advanced IT training at these IT Labs only. It is also desired that students should study the subject of Information systems controls and Audit concurrently while undergoing 100 Hours Advanced IT training. The training components would focus on application software relevant for accounting and auditing. Advanced features of MS-Access, MS Excel, CAAT, Core Banking Solution(CBS), Enterprise Resource Planning( ERP) and Office automation application and IT security in a CA’s office are the main components which would be covered during the training programme. This uniform course material has been prepared by ITT Section of IT Directorate of the ICAI in accordance with the course contents covered in the specially designed curriculum to disseminate quality education to its students and the same has been printed by The Board of Studies for distribution to CA students across India and abroad. We hope that this course material would help the students in building their IT skills which is a must for all, in the current scenario.
CONTENTS UNIT-1 : DATABASE APPLICATION USING MS-ACCESS ................................................................ 1 CHAPTER 1. ADVANCED SQL QUERIES ................................................................................................
3
CHAPTER 2. DESIGNING FORMS AND REPORTS ................................................................................ 69 CHAPTER 3. BUILDING CRITERIA EXPRESSIONS ................................................................................ 123 CHAPTER 4. MACROS AND SWITCHBOARDS ....................................................................................... 159 CHAPTER 5. DATA PAGES AND PROTECTION ...................................................................................... 213 CHAPTER 6. IMPORT/EXPORTING DATA .............................................................................................. 234
UNIT-2 : ADVANCE MS-EXCEL ...................................................................................................... 275 CHAPTER 1. WORKING WITH XML ......................................................................................................
277
CHAPTER 2. IMPORTING/EXPORTING DATA ...................................................................................... 298 CHAPTER 3. ADVANCES IN MACROS .................................................................................................. 312 CHAPTER 4. APPLIED FINANCIAL ANALYSIS ...................................................................................... 329 CHAPTER 5. STATISTICAL TOOLS IN EXCEL ...................................................................................... 362 CHAPTER 6. APPLICATION OF MS-EXCEL .......................................................................................... 382
UNIT-1 DATABASE APPLICATION USING MS-ACCESS
CHAPTER
1
ADVANCED SQL QUERIES
LEARNING OBJECTIVES Writing Advanced Queries Creating Sub-queries Creating Unmatched and Duplicate Queries Grouping and Summarizing Records using Criteria Summarizing Data using Crosstab Query Creating a Pivot Table and a Pivot Chart Joining Tables in Queries Calculated Fields
1.1. Introduction Queries are an essential part of database. They are used to extract required data from one or more tables and present the result in a datasheet or on a Form or Report. They can be considered as questions asked to a table in a database. Access 2010 provides a graphical tool known as Query Designer to create queries. Queries are not only used to retrieve data from tables, but can also be used to insert, update or append data in tables, to filter data, to perform calculations with data, to summarize data and to automate data management tasks. This chapter focuses on creating different types of queries and their different usage. The first part of the chapter talks about Sub-queries, in which the criterion for a query is query itself, i.e. writing a query within query. The next part of the chapter talks about working with Query Wizard and learning how to find unmatched data between two tables and to find duplicate rows within a table. We will also learn to create a summarised result out of queries using the crosstab queries. Crosstab queries can be taken as a tabular format of Pivot tables. This chapter also introduces the multiple views of the query and how to get query results in the form of Pivot Tables or Pivot Charts. In addition to the above queries, we will also learn to create a query on multiple tables, specify different join types to retrieve the desired result. We can create joins between the tables using relationship window provided by Access 2010, or we can create joins at the query design window. Access 2010 also has many functions and operators which can be used to create expressions. This chapter discusses how to use these functions to create a new column from an existing column. The chapter also highlights some of the advanced queries available in Access 2010 and illustrates their significance using case studies.
DATABASE APPLICATIONS USING MS-ACCESS
1.2. Writing Advanced Queries Access 2010 has the capability to handle far advanced queries than the simple criteria based queries. The queries in Access 2010 not only allow users to change the existing data, but also to generate summary reports. This section discusses few advanced queries handled by Access 2010, such as Sub-queries, Crosstab Queries, Creating Unmatched and Duplicate Queries, and also creating PivotTable and PivotChart through queries.
1.2.1 Creating Sub-queries A sub-query is a query nested inside another query. We can use Sub-queries within Select query, Action query or within other Sub-queries. Sub-queries in Select statement can be the part of Where clause or having clause in Group By query. For Action queries, we can use Sub-queries to change the records which match some values in other tables. Fig. 1.2.1 shows an example of a sub-query in a Select statement. SELECT * FROM Products WHERE ProductID IN (SELECT ProductID FROM OrderDetails WHERE Discount >= .25); Fig. 1.2.1. Subquery Example This query retrieves all the columns from table Products based on the criteria that the discount on the products in the OrderDetails table must be greater than or equal to 25%. Notice that to present the criteria of discount for Products, we have used a sub-query in the WHERE clause. Points to be noted while writing a sub-query:
The sub-query must always be written as an SQL statement.
The sub-query is always written in brackets ( ).
If we are using the same table for the main query and sub-query, we need to provide aliases (alternate names) to the tables.
If a sub-query is returning more than one row, the IN, ANY, ALL or EXISTS clause should be used in the WHERE statement.
Problem Scenario Rohit is an Accountant in Apex Ltd. At the closing of the quarter, he has to check the Invoices for which the payments are made in Quarter-I of year 2008. Solution For the purpose of solving the above requirement, a query is created to retrieve all records from Invoices table for which the Payment Date in Payments table lies in Quarter-I i.e. between 1/1/2008 and 4/30/2008. Since we do not require any details from the Payments table, we use the table in a sub-query. 4
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES Steps for retrieving records from table INVOICES 1.
Open the Show Table dialog box, by clicking on Create -> Queries -> Query Design.
2.
Select the Invoice table from Show Table window and click Add, as shown in Fig. 1.2.2.
Fig. 1.2.2: Show Table window 3.
Click Close.
4.
The Query Designer Window appears, as shown in Fig. 1.2.3.
Fig. 1.2.3: Query Designer Window ADVANCED INFORMATION TECHNOLOGY TRAINING
5
DATABASE APPLICATIONS USING MS-ACCESS 5.
Select the fields Invoice Number, Sales Order Number, Type of Invoice, Invoice Date, Source of Order and Payment Terms from table Invoice and drag them to the Columns tab as shown in Fig. 1.2.4.
Fig. 1.2.4: Drag the required columns 6.
Click the Save button at Quick Access Toolbar to save the query. Type the name of query as Invoices Paid Q1 as shown in Fig. 1.2.5.
Fig. 1.2.5: Save the Query 6
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES Now we create a SQL Statement for sub-query. The SQL Statement for the sub-query can be written directly in the criteria clause with the Select syntax or we may create another query using Query Designer and then copy the generated SQL. For the current scenario, we use the latter method. Steps for writing a query to retrieve Invoice Number from Payments where Paid Date is in Quarter-I of year 2008 1. Open the Show Table dialog box, by clicking on Create -> Queries -> Query Design. 2. Select the Payments table from Show Table window and click Add, as shown in Fig. 1.2.6.
Fig. 1.2.6: Show Table window 3. Click Close. 4. Double-click the columns Invoice Number and Date Paid so that they appear in the Columns tab in Query Design as shown in Fig. 1.2.7.
ADVANCED INFORMATION TECHNOLOGY TRAINING
7
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.7: Select Required columns 5. In the Criteria section of the Date Paid Column, write the criteria BETWEEN #1/1/2008# AND #4/30/2008# and clear the Show checkbox. The Query Design window should appear, as shown in Fig. 1.2.8.
Fig. 1.2.8: Specify the criteria 8
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES
6. Click the Run icon
in Design -> Results to view that the proper result is coming.
7. Click on SQL View from Design -> Results -> View drop-down to view the SQL statement of the query. The SQL statement appears for the query, as shown in Fig. 1.2.9.
Fig. 1.2.9: Query SQL View 8. Copy the SQL statement and switch to the Query window of Invoices Paid Q1. Steps to add a sub-query to Invoices Paid Q1 query 9. In the Criteria tab of Invoice Number column, type IN() and paste the copied query within the braces. The Query window appears, as shown in Fig. 1.2.10.
Fig. 1.2.10: Write subquery in Criteria ADVANCED INFORMATION TECHNOLOGY TRAINING
9
DATABASE APPLICATIONS USING MS-ACCESS 10. Click the Run icon
in Design -> Results to view that the proper result is coming.
In a similar manner as demonstrated by an example above, Sub-queries can be used as a SQL statement for criteria of Action queries, Group By queries etc. NOTE: We can also use Sub-queries as an expression to create a new column as a query result.
1.2.2 Creating Unmatched and Duplicate Queries Query Wizard available in Access 2010 can be used to create different types of queries. Along with several different queries, it also provides queries to find duplicate records in a table on the basis of one or more fields in a table. In a similar manner, we can create Unmatched Query to compare two tables and find the records that do not have matching values in given columns. 1.2.2.1
Unmatched Queries
Find Unmatched Records Query will examine the data found in two different tables/queries and compare the records based on a common field. It will return the records from the first table which do not have matching values in second table. The easiest way to create Unmatched Query is by using the Find Unmatched Query Wizard. After the wizard builds query, we can modify the query's design to add or remove fields, or to modify joins as required. Unmatched Query Wizard in Access 2010 asks for the names of the two tables to compare, and common field name between the tables. The wizard then confirms the fields that we wish to retrieve from the first table as a query result. Finally, the wizard prompts to enter the query name and creates the query. This type of query can help find records that have no corresponding records in other tables. For example, we may be looking for products that have not been sold in any order or may be for customers who have not placed any orders. Problem Scenario Ankur Mathur, Sales Head of Apex Ltd. wishes to reduce the production of few products. To analyse which products should not be produced further, he needs to find out the products which have not been ordered so far. Solution For the purpose of finding the unmatched products in Sales Item Description, we use Unmatched Query Wizard and find out products from Inventory table which do not have a matching Item Number in Sales Item Description table. Steps for creating Unmatched Query using Query Wizard: 1.
Open the Query Wizard by selecting Query Wizard from Create -> Queries, as indicated in Fig. 1.2.11.
Fig. 1.2.11: Open Query Wizard 10
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 2.
The New Query window appears, as shown in Fig. 1.2.12.
Fig. 1.2.12: New Query Dialog Box 3.
Select Find Unmatched Query Wizard from the New Query window and click OK, as shown in Fig. 1.2.13.
Fig. 1.2.13: Select Find Unmatched Query Wizard 4.
The Find Unmatched Query Wizard appears. Select the table Inventory and click Next, as shown in Fig. 1.2.14.
ADVANCED INFORMATION TECHNOLOGY TRAINING
11
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.14: Select Table Inventory 5.
Select the table Sales Item Description from second page of the wizard as we need to compare Inventory table to Sales Item Description table, as shown in Fig. 1.2.15. Click Next.
Fig. 1.2.15: Select Table Sales Item Description
12
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 6.
Now, we need to mark the common field in both the tables to be compared. For this example, select the Item Number in both Inventory and Sales Item Description table and click shown in Fig. 1.2.16. Click Next to move to next page.
button, as
Fig. 1.2.16: Match the common fields between two tables 7.
On the next page in wizard, select the columns that should be the part of query result and click Next. In this page, select Item Number, Class, Category, Sub Category, Description, Manufacturer, Model and Cost fields as shown in Fig. 1.2.17. Click Next to move to next page.
Fig. 1.2.17: Select the Fields ADVANCED INFORMATION TECHNOLOGY TRAINING
13
DATABASE APPLICATIONS USING MS-ACCESS NOTE: Use
button to move a selected field from Available fields to Selected fields,
button to move all fields from Available fields to Selected fields, field from Selected fields to Available fields, to Available fields. 8.
button to move selected
button to move all fields from Selected fields
Name the Query as “Products without Orders” in the final window that appears and click Finish as shown in Fig. 1.2.18.
Fig. 1.2.18: Name the query 9.
The result of the query appears as in datasheet form, indicating the products that do not have an order associated with them, as shown in Fig. 1.2.19.
Fig. 1.2.19: Query Result 14
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 1.2.2.2 Duplicate Queries The Duplicate Queries option creates a query that reports which records in a table are duplicated by matching one or more fields in the table. The Query Wizard first confirms which fields have to be used to check for duplication and then prompts to enter some other fields that may be a part of query result. Finally, Access 2010 accepts a name for the query and displays the results as a datasheet. This type of query is useful when we have no unique indexes or primary key in the table, or the data for the table is imported from a source where we do not have mechanism to check duplicate values. Problem Scenario Varun Gupta, a Chartered Accountant in Apex Ltd., is required to audit the invoices and the payments. While tracking the payments he noticed that multiple invoices have been created for a single sales order. To sort out the things, he wishes to check all the sales order having duplicate invoices. Solution Create a Find Duplicate Query for table Invoices based on the field Sales Order Number so that it displays all the duplicate invoices created for a single sales order. Steps for Finding Duplicate records in the table Invoices 1.
Open the Query Wizard by selecting Query Wizard from Create -> Queries.
2.
Select Find Duplicates Query Wizard from the New Query dialog box and click OK, as shown in Fig. 1.2.20.
Fig. 1.2.20: Select Find Duplicates Query Wizard 3.
The Find Duplicates Query Wizard appears. Select the table Invoice and click Next as shown in Fig. 1.2.21. ADVANCED INFORMATION TECHNOLOGY TRAINING
15
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.21: Select Table Invoice 4.
Select the column on the basis of which the duplicate records need to be matched and click Next. In this scenario, select Sales Order Number as shown in Fig. 1.2.22. Click Next.
Fig. 1.2.22: Select the column for Duplicate values 16
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 5.
Select the columns that should be the part of the query result and click Next. In this dialog box, select Invoice Number, Type of Invoice, Invoice Date, Source of Order and Payments Terms, as shown in Fig. 1.2.23. Click Next.
Fig. 1.2.23: Select the columns for Query Result 6.
Name the Query as “Duplicate Invoices” in the final window that appears and click Finish, as shown in Fig. 1.2.24.
Fig. 1.2.24: Name the Query ADVANCED INFORMATION TECHNOLOGY TRAINING
17
DATABASE APPLICATIONS USING MS-ACCESS 7.
The result of the query appears in Datasheet form with all the Sales Order having multiple invoices, as shown in Fig. 1.2.25.
NOTE: We can create Find Duplicate Query by matching records on multiple fields also. This query can also be used to find duplicate records in a table by matching records on all the fields (considering that we can match only 10 fields at a time).
Fig. 1.2.25: Query Result
1.2.3 Grouping and summarising Records using Criteria Access 2010 provides queries that can be used for obtaining the aggregated results instead of individual records. These queries may be helpful in retrieving count of records, sum, average, and maximum or minimum of the values in a column. These queries are known as Group By queries or Totals Query. Such queries can return the aggregated results from the entire table or the records of the table filtered by a certain criteria. 1.2.3.1 Grouping and summarising Records At times, it is required to retrieve information in tables based on a group of one or more fields. For example, total number of contacts from a particular area or a sum of all the payments received in a month. Access 2010 provides a method to obtain the desired result using queries without the need of any complex programming. It calculates the totals using several aggregate functions. Access 2010 performs grouping of the records by using Totals option available in the Query Tools tab, as shown in Fig. 1.2.26. 18
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES
Fig. 1.2.26: Totals option in Design tab The Totals option adds a new row in the Query Designer window which enables the application of summary functions to columns as indicated in Fig. 1.2.27.
Fig. 1.2.27: Total Row added A list of Aggregate Functions that can be used with Totals Query is given in Table 1.2.1. FUNCTION NAME
EXPLANATION
Sum()
Returns the sum of numeric data for a column or set of values in a column
Count()
Counts the set of values that satisfy the given criteria
Avg()
Returns average of numeric data for a column or set of values in a column
Max()
Returns a maximum value from a set of values
Min()
Returns a minimum value from a set of values
Var()
Returns the variance of values in a column or set of values
Stdev()
Returns a standard deviation for a set of data values
First()
Returns the first value from a list of text values
Last()
Returns the last value from a list of text values Table 1.2.1: Aggregate Functions
Problem Scenario: The Country Head in Apex Ltd. wishes to compute the sales volume of its products. He also would like to see the number of orders placed for each product, so that they can focus on products with greater sales volume.
ADVANCED INFORMATION TECHNOLOGY TRAINING
19
DATABASE APPLICATIONS USING MS-ACCESS Solution: Create a Total query that calculates the count of orders placed for each product and arrange them in descending order of the counts so as to find the products which are sold more. Steps for creating a total query 1.
Open the Query Design window by selecting Query Design from Create -> Queries, as indicated in Fig. 1.2.28.
Fig. 1.2.28: Opening the Query Design window 2.
Select the Inventory and Sales Item Description tables from Show Table dialog box and click Add, as shown in Fig. 1.2.29.
NOTE: Multiple tables can be selected in the Show Table window by pressing CTRL key and then selecting the tables.
Fig. 1.2.29: Show Table window 3.
Click Close. We can see the two tables with a 1:∞ relationship. This relationship has been created while creating the database.
4.
Click the Totals button in the Show/Hide group on the Design tab, as shown as Fig. 1.2.30.
20
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES
Fig. 1.2.30: Click on Totals button 5.
Select the fields Category and Item Number from Inventory table and drag them to the Columns tab. Similarly, select fields Sales Order Number from Sales Item Description table and drag it to Columns tab. The Query Window appears as shown in Fig. 1.2.31.
Fig. 1.2.31: Select the required columns 6.
In the column Sales Order Number, change the Group By function to Count, as shown in Fig. 1.2.32. ADVANCED INFORMATION TECHNOLOGY TRAINING
21
DATABASE APPLICATIONS USING MS-ACCESS Notice that we have set Group By on columns Category and Item Number, so that the query first groups all the items according to their category and then all the items in same category on the basis of Item Number. The Count function with Sales Order Number indicates that we wish to compute the count of total Sales Orders for a group created.
Fig. 1.2.32: Set the Totals Function 7.
Click Run
in Design -> Results to view the results. The result of the query appears, as shown in
Fig. 1.2.33.
22
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES
Fig. 1.2.33: Query Result NOTE: The Query result just shows all the products arranged in group of Category and Item Number and their volume sold. To get the products which are sold more, the column CountOfSales Order Number has to be arranged in order that it appears from most sold to least sold. 8.
Reopen the query in Design View by clicking Design View from Home -> Views.
9.
In the column Sales Order Number, set the sort order as descending, as shown in Fig. 1.2.34.
ADVANCED INFORMATION TECHNOLOGY TRAINING
23
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.34: Set the sort order 10. Click Run
24
in Design -> Results to view the result. The result appears as shown in Fig. 1.2.35.
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES
Fig. 1.2.35: Query Results sorted according to sales of Product 11. Click the Save button Product Sales Volume.
on Quick Access Toolbar to save the query. Type the name of query as
NOTE: Queries are required to be saved for future use if the same result is desired again; it saves the effort and time of recreating the query. 1.2.3.2 Applying Criteria to Records A criterion limits the records that are displayed as result, on the basis of values in a field. A criterion in Total queries can be created against Group By, Aggregate Total, Non-Aggregate Total fields. For Group By and Aggregate Total, criteria can be mentioned using Criteria tab of Query Design window. For the Non-Aggregate Total field, the criteria can only be specified using the Where clause instead of Group By or Aggregate function in Total tab of Query Design window. Using any one, any two, or all three of these criteria, the scope of Total query can be limited to finite criteria. Problem Scenario Considering the problem of retrieving Sales volume of Products as discussed in Section 2.2.3.1, Country Head wants to have a look at only the products with at least an order count of three. The management authority also thought of maintaining the products which are cheaper and have more sales volume. Solution Update the Total query Product Sales Volume created above and apply criteria “>=3” on the Sales Order Number count to ensure that only the products with at least an order count of three are retrieved as a query result. Also, add criteria “<50” to the Cost field of the products so that management can have a view on the cheaper products. ADVANCED INFORMATION TECHNOLOGY TRAINING
25
DATABASE APPLICATIONS USING MS-ACCESS 1.
Open the query Product Sales Volume in Design view. To do this, right-click the query and select Design View.
2.
In the column Sales Order Number, type “>=3” in the Criteria tab as shown in Fig. 1.2.36.
Fig. 1.2.36: Insert Criteria for Sales Order Number 3.
Click Run
in Design -> Results to view the result. The result of the query appears as shown in Fig.
1.2.37.
26
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES
. Fig. 1.2.37: Query Result for Products having at least 3 Sales Orders Now, include only the products which cost less than 50.00 in the query result. Since Cost is a nonaggregate field, the criteria for the Cost is included in the Where clause of Total tab. 4.
Double-click the field Cost in the Inventory table so as to include it into the Field tab of Query Design window.
5.
Change the Group By function of column Cost to Where clause in Total tab and write “<50” in the Criteria tab, as shown in Fig. 1.2.38. Note that the Show checkbox is cleared as Cost is a non-aggregate field and not a part of the query result.
ADVANCED INFORMATION TECHNOLOGY TRAINING
27
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.38: Products with cost <50 6.
Click Run
in Design -> Results to view the result of the query, as shown in Fig. 1.2.39.
Fig. 1.2.39: Query Result 28
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 7.
Click Save
at Quick Access Toolbar to save the query.
1.2.4 Grouping and summarizing Records using a Crosstab Query Crosstab query is an excellent analytical tool. It is a special type of query that can be created to describe one numerical quantity in terms of two other fields. Crosstab queries are useful for summarizing information, and are somewhat similar to pivot tables in MS-Excel. For example, we might want to have a table that contains the sales figures of entire inventory for the whole year, and the amount of money that is made per product during each month of the year. In this case, a crosstab query would be the right way to display the information. Access 2010 provides an option to create Crosstab query through Query Wizard. Each crosstab query will include one or more Row Heading, a single Column Heading and a Value to be displayed at the intersection of row and column. Problem Scenario The company Apex Ltd. wishes to revise the credit limit of its customers. For this purpose, Ashish, the PRO needs a summary report that indicates the count of orders placed by each customer in every month of last financial year i.e. 2011-2012. Solution To obtain the desired summary report, create a Crosstab query on table Sales Order with month of Sales Date as row heading, Customer Number as column heading and count of Sales Order Number as values. We create this query using the Query Wizard. Steps for creating Crosstab queries 1.
Open the Query Wizard by selecting Query Wizard from Create -> Queries
2.
Select Crosstab Query Wizard from the New Query dialog box and click OK as in Fig. 1.2.40.
Fig. 1.2.40: Select Crosstab Query Wizard ADVANCED INFORMATION TECHNOLOGY TRAINING
29
DATABASE APPLICATIONS USING MS-ACCESS 3.
The Crosstab Query Wizard appears. Select the table Sales Order and click Next as shown in Fig. 1.2.41.
Fig. 1.2.41: Select Table Sales Order 4.
The next page in Query Wizard confirms the column to be taken as Row Heading. In this window, select the column Sales Date as shown in Fig. 1.2.42 and click Next.
Fig. 1.2.42: Select column Sales Date for Row Heading 30
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 5.
Select the column to be taken as Column Heading in the next window of the Query Wizard that appears. In this window, select the column Sold to Customer as shown in Fig. 1.2.43 and click Next.
Fig. 1.2.43: Select column Sold to Customer for Column Heading 6.
Next page in the wizard prompts to specify the values that should appear on the intersection of rows and columns. Select the column Sales Order Number from the Fields tab and Count from the Functions tab in this page, as shown in Fig. 1.2.44. Click Next.
NOTE: This page has a checkbox Yes, include row sums; which if checked, allows the inclusion of the grand total of values in the row as a column in the query result.
ADVANCED INFORMATION TECHNOLOGY TRAINING
31
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.44: Select Sales Order Number Count as values 7.
Write the name for the query as “Customer-Month wise Sales” in the final window that appears and click Finish, as shown in Fig. 1.2.45. We can also choose the default query name that the wizard displays.
Fig. 1.2.45: Name the query 32
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 8.
The result of the query appears in Datasheet form, as shown in Fig. 1.2.46.
Fig. 1.2.46: Query Result NOTE: The query result is not as desired as it displays the values on the basis of the Sales Date and not on Sales Month. To view these results on the basis of Sales Month, we are required to make changes in the query design and change the column Sales Date to the Month (Sales Date) and also provide a criterion that the months must be in last financial year. Steps to group results on Sales Order Month 1.
Reopen the query in design view by clicking the Design View from Home -> Views.
2.
Click on field Sales Date and write the expression Sales Month: Month ([Sales Date]) in Field tab as shown in Fig. 1.2.47.
NOTE: We can use the function Month Name () to get names of month instead of numbers in query results.
ADVANCED INFORMATION TECHNOLOGY TRAINING
33
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.47: Change the expression of field Sales Date Steps to provide the criteria for last financial year 1. Double-click the column Sales Date from table Sales Order such that it appears in Field tab. Change the value of Total tab to Where and add the expression Between 4/1/2011 AND 3/31/2012 to the Criteria tab as shown in Fig. 1.2.48.
Fig. 1.2.48: Provide a criteria to Sales Date column 34
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES NOTE: The Access 2010 query window has changed the criteria expression suitable to match column values. 2. Click Run
in Design -> Results to view the modified result as shown in Fig.1.2.49.
Fig. 1.2.49: Query Result NOTE: The result of the query appears as a 3-dimensional table with Months on rows, Customer No. on columns and the Count of orders as values. Crosstab Queries are capable of handling much more complex calculations. These queries can be based on another query using multiple tables or may use different level of grouping by having more than one row heading. Also, Crosstab queries can be created by Query Design by changing the query type to Crosstab.
1.2.5 Creating a PivotTable and PivotChart The powerful tool of MS-Excel PivotTable and PivotChart is also available in Access 2010 to summarize data. Interactive Pivot Tables and Pivot Charts enable the manipulation of summary data, and therefore can save ample time to create multiple queries and reports to achieve the same results. 1.2.5.1 PivotTable A PivotTable is a view in Access Queries that allows summarising and examining data in a datasheet form. It is used to group values as rows and columns with a calculated value at the intersection of each row and column. A PivotTable can be considered as a modified form of Crosstab queries discussed in the above section. A PivotTable is created by dragging fields to the appropriate area on the design screen. Data can also be broken down to different levels of detail, such as showing earnings by year, quarter, or month. The PivotTable view in a query can be obtained by selecting the PivotTable View from the Views drop-down in Home tab as indicated in Fig. 1.2.50.
ADVANCED INFORMATION TECHNOLOGY TRAINING
35
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.50: PivotTable View The PivotTable is shown in Fig. 1.2.51.
Fig. 1.2.51: PivotTable A PivotTable has four areas for dropping fields whose values are summarized. The description of these areas is shown in Table 2.2.2.
36
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES Drop Area
Description
Filter Area
Is used for the fields that are used as a filter for PivotTable
Column Area
The fields selected to be displayed as column headings are included in this area
Row Area
The fields selected to be displayed as row headings are dropped in this area
Totals Or Detail Area
The field values to be used for calculations or summarization are dragged and dropped in this area, and the value is displayed at the intersection of a row and column Table 1.2.2: Drop Area in Pivot Table
Problem Scenario The Head of Sales Department in Apex Ltd. has demanded a Sales Summary report for review. The following are the desired requirements: the sales of the products can be viewed in terms of Year, Quarters and Months; the report should enable the user to view the products filtered by Category. Solution To create this Summary report, first a query is created that displays the Products and their Category, Sales amount of each product, and also the date on which they were sold. Then to create summary sheet, we create a PivotTable view of the query having:
Category field as a filter
Product field on row
Year, Quarter and Month on columns
Total Sales (which is computed as Quantity sold into Product cost) displayed as values
Steps for creating the query to obtain Sales Data 1.
Open the Query Design window, by clicking Create -> Queries -> Query Design.
2.
Select the Inventory, Sales Item Description and Sales Order tables from Show Table window and click Add, as shown in Fig. 1.2.52.
ADVANCED INFORMATION TECHNOLOGY TRAINING
37
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.52: Show Table window 3.
Select the columns Category and Item Number from Inventory Table and drag them to the columns tab. Similarly, select column Sales Date from table Sales Order and drag it to the columns tab. The query window appears as in Fig. 1.2.53.
Fig. 1.2.53: Select the required columns 38
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 4.
Now to compute the Total Sales of the Product, multiply Quantity * Price and create a new column. Write the expression Total Sales: [Quantity]*[Price] in the Field tab of the next column as displayed in Fig. 1.2.54.
Fig. 1.2.54: Compute Total Sales 5.
Click Run
in Design –> Results to view the query result. The result appears as shown in Fig.
1.2.55.
Fig. 1.2.55: Query Result ADVANCED INFORMATION TECHNOLOGY TRAINING
39
DATABASE APPLICATIONS USING MS-ACCESS Now, we have achieved the desired result from the query. However, the Summary Report through PivotTable is required to be created. Steps for Creating PivotTable from the query 1. Open the query in PivotTable View by clicking PivotTable View from Home -> Views, as displayed in Fig. 1.2.56.
Fig. 1.2.56: Select PivotTable View 2.
The PivotTable view appears with the field list on right side as displayed in Fig. 1.2.57.
Fig. 1.2.57: PivotTable View 40
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES NOTE: If the PivotTable Field List does not appear, obtain the list by clicking Field List from Show/Hide group on the Design tab as indicated in Fig. 1.2.58.
Fig. 1.2.58: Field List Button 3. Select the Category field from PivotTable Field List and drag it to the Drop Filter Fields Here area. 4. Select the Item Number field from PivotTable Field List and drag it to the Drop Row Fields Here area. 5. Select the Year by expanding the Sales Date By Month field and drag it to the Drop Column Fields Here area. Similarly, select and drag Quarter and Month to the Drop Column Fields Here area. 6. Select and drag the Total Sales field to the Drop Totals or Detail Fields Here area. The PivotTable window should appear as in Fig. 1.2.59.
Fig. 1.2.59: Drag Fields in PivotTable Area 7. Click Save at Quick Access Toolbar to save the query. Type the name of the query as “Sales Summary Report”. If we wish to see the Quarterly sales of all the Products from Personal Watercraft category, the PivotTable query is obtained as follows:
ADVANCED INFORMATION TECHNOLOGY TRAINING
41
DATABASE APPLICATIONS USING MS-ACCESS 8. Open the drop-down in Category Filter Area, clear all checkboxes and check the Personal Watercraft and click OK as in Fig. 1.2.60.
Fig. 1.2.60: Select Personal Watercraft from Category Filter 9. Click on the negative sign on Quarter tab so that the months disappear. Also, click on the plus sign with Totals to make the Grand Total appear. Make sure that all the plus signs in Item Number Row are clicked so as to make the Total Sales value appear. The final query should appear as shown in Fig. 1.2.61.
42
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES
Fig. 1.2.61: Quarterly sales of all the Products from Personal Watercraft category 1.2.5.2 PivotChart A PivotChart is a tool used for graphical analysis of data. In simple terms, PivotChart helps visualize a PivotTable, Query or a Form. It can display summarized data in different chart formats and enables data analysis. Data can be presented by using different chart formats as required, and unwanted items can be hidden from being viewed. The PivotChart view in a query can be obtained by selecting the PivotChart View from Home -> Views, as indicated in Fig. 1.2.62. ADVANCED INFORMATION TECHNOLOGY TRAINING
43
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.62: PivotChart View A sample PivotChart indicating sales of a Category of Products in each Quarter in a year is shown in Fig. 1.2.63.
Fig. 1.2.63: PivotChart View 44
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES Description of the various headings marked in PivotChart above is given in Table 2.2.3. Headings
Description
X-Axis
The horizontal axis in PivotChart
Y-Axis
The vertical axis in PivotChart
Legend
A table displaying the color code used for each data series in PivotChart
Filter Field
A field on basis of which filter can be applied on PivotChart.
Data Field
Field values to be shown along the Y-axis.
Category Field
Field values to be shown along the X-axis.
Series Field
Field values that will form the legend of the graph. Table 1.2.3: Various fields in PivotChart
Problem Scenario Considering the Summary Sales Report discussed in Section 1.2.5.1, a graphical representation of the same data is required. Solution To represent the data graphically, we need to create a PivotChart. For this purpose, we first create a query to display Summary Report and then create a PivotChart based on that query. In the Pivot Chart, the fields will be placed as:
Category as Filter Field
Years & Quarters field on X-Axis
Total Sales on Y-Axis
Item Number as Series Field
Steps to create a query of Summary Report Follow the steps discussed in Section 1.2.5.1 to create a query Sales Summary Report and create another query Graph of Sales Summary Report with columns as Category, Item Number, Sales Date and Total Sales (Quantity * Price). Steps to create a copy of Summary Report 1.
Double-click the Graph of Sales Summary Report query to open it in the Datasheet view.
2.
Open the PivotChart view of the query by selecting PivotChart View from Home -> Views drop-down list. The PivotChart view appears as in Fig. 1.2.64.
ADVANCED INFORMATION TECHNOLOGY TRAINING
45
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.64: PivotChart View 3.
If the Chart Field List is not there, select the Field List option from the Show/Hide group on the Design tab.
4.
Select the Category field from Chart Field List and drag it to the Drop Filter Fields Here area.
5.
Select Years by expanding the Sales Date By Month field and drag it to the Drop Category Fields Here area. Similarly, select and drag Quarters to the Drop Category Fields Here area.
6.
Select the Item Number field and drag it to the Drop Series Fields Here area.
7.
Select and drag the Total Sales field to the Drop Data Fields Here area.
8.
To display the legend, select Legend from the Show/Hide group on the Design tab, as indicated in Fig. 1.2.65.
Fig. 1.2.65: Select Legend option 46
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 9.
The PivotChart window should appear, as shown in Fig. 1.2.66.
Fig. 1.2.66: Drag and Drop Fields in PivotChart Area NOTE: The Total Sales of few products is much lesser as compared to other products that they are hardly visible on data bar. To solve this problem, the axis has to be changed to Logarithmic axis so as to make data bars more visible. Steps for changing the axis to logarithmic axis 1. Right-click on any value in Y-axis so the entire scale is selected and select Properties from the menu, as shown in Fig. 1.2.67.
ADVANCED INFORMATION TECHNOLOGY TRAINING
47
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.67: Select properties for Y-Axis 2. In the Properties window that appears, go to the Scale tab and check Logarithmic Scale checkbox as displayed in Fig. 1.2.68.
Fig. 1.2.68: Scale Properties 48
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 3. Close the Properties window. In order to make graph more explanatory, we will provide a name to X-Axis and Y-Axis of the graph. Steps for naming Axis in PivotChart 1. Right-click the Axis Title on X-Axis and select Properties from the menu, as shown in Fig. 1.2.69.
Fig. 1.2.69: Open X-Axis Properties 2. In the Properties window, go to the Format tab and change the Caption property to Sales Quarter as in Fig. 1.2.70.
ADVANCED INFORMATION TECHNOLOGY TRAINING
49
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.70: Change caption of X-Axis 3. In a similar manner, change the caption of Y-Axis to Total Sales. The PivotChart appears as in Fig. 1.2.71.
Fig. 1.2.71: Pivot Chart with Axis Captions 50
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES Now if we wish to see the chart of quarterly sales of all the products from Truck category for the year 2011, the PivotChart will be obtained as follows: 4. Open the drop-down in the Category Filter area, clear all checkboxes check the Truck checkbox and click OK as in Fig. 1.2.72.
Fig. 1.2.72: Select Truck from Category 5. In a similar manner, select 2011 from Years drop-down in horizontal axis. The resultant chart appears as in Fig. 1.2.73 indicating the sale of different items of Truck category, which is maximum in Quarter2 and minimum in Quarter4.
ADVANCED INFORMATION TECHNOLOGY TRAINING
51
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.2.73: Quarter-wise Truck Sales NOTE: Different PivotCharts can be made to represent different kinds of data. Both PivotChart and PivotTable can also be made directly on tables rather than making a query first.
1.3. Joining Tables in Queries A Join is a temporary relationship that is created between two tables in a query or the relationship window using a common field in both the tables having same data type and usually the same name. Joins created in a query are temporary and are meant for the current query only. Joining tables in a query is required to view data from two or more tables. For example, to retrieve products ordered by each customer, tables Customers, Sales Order and Inventory are required to be joined to get the desired output. When two or more tables are added to the Query Design window, Access 2010 creates Joins between them based on the relationships that have been defined in the relationship window. Joins establish the criteria that the data must match to be included in the query operations. If the tables are not joined, the query result will match each record of one table to every record in another table, resulting in spurious rows. Different types of joins are available to get a different set of records as query result. There are three types of joins available in Access 2010: inner join, left outer join, and right outer join. Inner Join: Returns only those rows from both tables that match on the joining field. Left Outer Join: The query returns all of the rows from left table, and also those rows from the right table that share a common value on both sides of the join. Since some of the rows in left table of a left outer join will not have corresponding rows in right table, some of the fields returned as a query result will be empty when the rows do not correspond. 52
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES Right Outer Join: It is just the opposite of left outer join. The query using right outer join returns all the rows from right table, and also those rows from the left table that share a common value on both sides of the join. Problem Scenario The Operations Regional Head of Apex Ltd. is required to produce a report giving the details of the payments received. For this purpose, two reports are required to be prepared:
First report indicating the Invoices for which payments have been made, including the invoice and payments detail.
Second report displaying a list of all the sales order, their invoices and details of payments, including those invoices for which payments have not been received.
Solution To get the desired result, we create two queries: First query to fulfill the requirement using inner join between tables Invoice and Payments. Second query to achieve the second requirement which includes Sales Order, Invoice and Payments tables with an left outer join between Invoice and Payments tables. Steps to create the first query - to obtain invoices for which payments have been made 1.
Open the Query Design window, by clicking Create -> Queries -> Query Design.
2.
Select the Invoice and Payments tables from Show Table window and click Add. Click Close.
3.
To join the two tables, click the Invoice Number from Invoice table and drag it to Invoice Number in Payments table. The query window appears, as shown in Fig. 1.3.1. NOTE: If the tables are already related through relationship window, the joining line automatically appears between the tables.
ADVANCED INFORMATION TECHNOLOGY TRAINING
53
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.3.1: Create Relationship between tables 4.
Select the columns Invoice Number, Sales Order Number, Type of Invoice, Invoice Date and Source of Order from the table Invoice and drag them to the columns tab. Similarly, select columns Date Paid, How Paid, Amount Paid and Amount Alloc from Payments table and drag them to the columns tab. The query window appears as shown in Fig. 1.3.2.
Fig. 1.3.2: Add required columns 54
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 5.
Click the Save button Payment Made.
6.
Click the Run icon
on Quick Access Toolbar to save the query. Type the name of the query as
in Design -> Results to view the query result displaying invoices with their
payment details as shown in Fig. 1.3.3.
Fig. 1.3.3: Query Result Steps to create the second query - to display list of all the sales order, their invoices and payments details, including those invoices for which payments have not been received 1.
Open the Query Design window, by clicking Create -> Queries -> Query Design.
2.
Select the Sales Order, Invoice and Payments table from Show Table window and click Add. Click Close.
3.
To join the tables, click the Sales Order Number from Sales Order table and drag it to the Sales Order Number in Invoice table. Similarly, join Invoice and Payments table on Invoice Number field. The query window appears as shown in Fig. 1.3.4.
ADVANCED INFORMATION TECHNOLOGY TRAINING
55
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.3.4: Join Tables 4.
56
Select the fields Sales Order Number, Sold to Customer and Sales Date from Sales Order table and drag them to the Columns tab. Similarly, select fields Invoice Number, Type of Invoice, Invoice Date, Source of Order and Payment Terms from Invoice table and columns Date Paid, How Paid, Amount Paid and Amount Alloc from Payments table. The query window appears as in Fig. 1.3.5.
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES
Fig. 1.3.5: Select required columns 5.
Click Run
in Design -> Results to view the query result as shown in Fig. 1.3.6.
Fig. 1.3.6: Sales Order with Payments ADVANCED INFORMATION TECHNOLOGY TRAINING
57
DATABASE APPLICATIONS USING MS-ACCESS Notice that these query results are showing only the records for which payments have been received. To get the records for which the payment are not yet received, the join between Invoice and Payments table has to be converted to left outer join. Steps to create left outer join between Invoice and Payments tables 6.
Switch to the query design view by clicking Design View in Home -> Views.
7.
Right-click the joining line between Invoice and Payments tables and select Join Properties from the menu, or double-click the joining line. The Join Properties window appears, as shown in Fig. 1.3.7.
Fig. 1.3.7: Join Properties dialog box 8.
Select the option 2: Include ALL records from ‘Invoice’ and only those records from ‘Payments’ where the joined fields are equal., and click OK. The Join Properties window appears as displayed in Fig. 1.3.8.
Fig. 1.3.8: Set the Join Properties to Left Outer Join
58
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 9.
The Join line changes to indicate that it is a left outer join. Notice an arrow pointing towards the Payments table as indicated in Fig. 1.3.9.
Fig. 1.3.9: Left Outer Join between Invoice and Payments tables 10. Click Save Details.
on Quick Access Toolbar to save the query. Type the name of the query as Sales Order
11. Click Run
in Design -> Results to view the query result shown in Fig. 1.3.10. Notice that the Date
Paid, How Paid, Amount Paid and Amount Alloc fields from table Payments are blank for few records, indicating the invoices for which payments have not been received.
ADVANCED INFORMATION TECHNOLOGY TRAINING
59
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.3.10: Query Result A more complex join can be created among any number of tables and modified accordingly to get the desired results.
1.4. Calculated Fields The Access 2010 query’s result is not restricted to the fields in tables only, but can display many other computed columns known as Calculated Fields. The Calculated fields can be compared to cells containing functions or formulas in Excel Worksheet. In Access, these cells can be considered as the columns of the table. Normalization forbids tables to have columns whose values can be computed using the existing fields. Calculations in a query are recomputed each time the query is run. As such, data is always current. The results of the calculations are not stored in a table. A calculated field performs some type of arithmetic calculations on one or more fields in a table to come up with a completely new field. For example, if a table has an Order Total field and a Tax Rate field, Access 2010 can calculate these two fields to find out the Sales Tax for each order as [Order Total] * [Tax Rate]. The calculated fields create new fields in a record by combining the values of other fields in the record. Calculated fields can store numeric, date, or text fields for each record using expressions and functions. Problem Scenario Ramit, an executive in Apex Ltd. is required to produce a report displaying all the sales orders which contains the field Total Amount Paid as a sum of Tax, Freight and Other Charges. Solution As a solution to the above problem, a query has to be created on table Sales Order with a calculated column Total Amount Paid computed as a sum of Tax, Freight and Other Charges. 60
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES Steps for creating query with Calculated Columns 1.
Open the Query Design window, by clicking Create -> Queries -> Query Design.
2.
Select the Sales Order table from Show Table window and click Add. Click Close.
3.
Select the columns Sales Order Number, Sold to Customer, Sales Date, Payment Terms and Shipped via from Sales Order table and drag them to the columns tab as displayed in Fig. 1.4.1.
Fig. 1.4.1: Select Required Columns 4.
To create the calculated column, write the expression Total Amount Paid: [Tax] + [Freight] + [Other] in the Field tab of the next column as displayed in Fig. 1.4.2.
ADVANCED INFORMATION TECHNOLOGY TRAINING
61
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 1.4.2: Calculated Column - Total Amount Paid 5.
Click Run
in Design -> Results to view the query result. The result is displayed in Fig. 1.4.3. Note
the calculated column Total Amount Paid in query result.
62
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES
Fig. 1.4.3: Query Result 6.
Save the query as Sales Order Report and close the query window.
1.5. Summary Queries are the heart of every database application. Queries are responsible for converting diffuse data contained in tables into information that users can actually use. Without queries, we would have to write a complex code for every data extraction and transformation. This chapter talks about more complex part of queries. Sub-queries, as the name indicates is a query within query and helps us to retrieve data from multiple tables, and can also be used to replace Joins. The Query Wizard can be used to create queries like Find Unmatched and Find Duplicate. Apart from this, queries can generate summary reports using Group By and Crosstab Queries. Queries can be very interactive in terms of PivotTables and PivotCharts which can be obtained by just changing the query view. Queries can be based on multiple tables using different types of joins. Joins can be Inner Join or Outer Joins. Queries provide much more liberty, such as adding newly calculated columns to query result or restrict number of rows returned by specifying the criteria. Calculated columns enable us to implement normalization by omitting unnecessary columns in the table and introducing them as calculated columns later.
ADVANCED INFORMATION TECHNOLOGY TRAINING
63
DATABASE APPLICATIONS USING MS-ACCESS
Lab Exercises Case Study For the database Apex Inventory Shipment of Apex Ltd., consider the scenario and provide their solutions. 1. The company is launching a new sales campaign for its existing customers. For this, the marketing department needs the list of customers with the highest credit limit. Create a query using sub-query to retrieve this list. 2. A sales person made a mistake and skipped entering the item description for an order made by the customer. Using query, retrieve the sales order information for which the item description has not been entered. 3. For the above exercise, retrieve the information about the customer who has placed the order so that the items can be reconfirmed. 4. The company launched its new office in India and asked the sales executive to interact with various people and enter the details of possible customers in a table named Customers_India. The table has the following structure: Field Name Customer Number Salutation First Name Last Name Company Phone Email Street City State ZIP Code
Data type Text Text Text Text Text Text Text Text Text Text Text
In the absence of any constraints on the table, the sales team ended up inserting duplicate records of a single customer. Write a query to find these duplicate records. (Consider the Customer Number as unique for each customer.) 5. The Finance Head who keeps track of their inventory shipped, requires the report displaying the quantity of items shipped every month of year 2011. Create a Totals query displaying the required data. 6. The company is issuing a discount policy to its customers. For this purpose, the Marketing Regional Manager needs a detailed report of the customers. The report should contain Customers Names on rows and Month Name as columns, and count of orders placed by each customer on the intersection cells of rows and columns. 64
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES 7. Create a user interactive report using PivotTable to display payments made by customers. The user should be able to filter the customers according to their states and should be able to drill the payments in terms of years, quarters, months and days. 8. Considering the scenario given in the above exercise, create a graphical view using PivotChart indicating the total payments received quarter-wise from all the customers from a particular city. User should be able to filter the city on the basis of their country. 9. Create a query containing mailing address list for all the customers with the following field list: 1 Salutation FirstName Last Name 2 Company 3 Street, City 4 State 5 Country 6 Postal Code 10. Display the list of all customers from New York (State Code – NY), with details of items they have ordered and Total Amount to be paid by them. Multiple Choice Questions 1. For the database Apex Inventory Shipment of the Apex Ltd., we wish to retrieve records for customers who have not placed any orders yet. What type of query can be used? (a)
Duplicate Query
(b)
Crosstab Query
(c)
Find Unmatched Query
(d)
Group By query
2. Considering the database Apex Inventory Shipment of the Apex Ltd., how can we display sales grouped by country, state, and customer, all at the same time? (a)
Use the Sort Descending command
(b)
Use the PivotTable View command
(c)
Use the Find command on specified groups
(d)
All of the above
3. For the database Apex Inventory Shipment, the number of items for each category is required to be computed, which query type is required to be used? (a)
Select Query
(b)
Group By query
(c)
Crosstab Query
(d)
Duplicate Query ADVANCED INFORMATION TECHNOLOGY TRAINING
65
DATABASE APPLICATIONS USING MS-ACCESS 4. Considering the scenario in question above, which function should be used with Item Number in query? (a)
Count
(b)
Compute
(c)
Sum
(d)
Calculate
5. In the database Apex Inventory Shipment, to see total amount received from Payments table, it should be dragged into which area of the PivotTable? (a)
Drop Column Fields Here
(b)
Drop Row Fields Here
(c)
Drop Totals or Detail Fields Here
(d)
None of the above
6. Considering the database Apex Inventory Shipment, we wish to get all the sales orders with cash payments. What needs to be done to achieve this? (a)
Create a sub-query with Sales Order as Payment type
(b)
Create a select query on Sales Order table and write Cash as criteria for Payment Terms
(c)
Create a Group-By query on Payment Terms
(d)
None of the above
7. From the database Apex Inventory Shipment, we wish to retrieve a report displaying details of all the invoices including the payments details (if already made) of the invoices. What type of Join should be used in Query window to achieve the desired result? (a)
Left outer join
(b)
Right outer join
(c)
Default join
(d)
No joins will be used
8. How can we add a table to the Query Design window? (a)
Select Create -> Add Table
(b)
Select Database Tools -> Add Table
(c)
Select Design -> Show Table
(d)
Select the table from the Navigation Pane
9. If we are creating a Crosstab query, the table we are querying must contain what?
66
(a)
Lots of confusing information
(b)
More than 100 records ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCED SQL QUERIES (c)
At least one field
(d)
At least three fields
10. _______ type of query summarises information in a grid, organized by regions and months. (a)
An update query
(b)
A parameter query
(c)
An action query
(d)
A Crosstab query
11. When we double click a query object, we open (a)
The object in design view
(b)
The object in print preview
(c)
The result of the query
(d)
The underlying table on which the query is based
12. What is the primary difference between a PivotTable report and a Crosstab query? (a)
A PivotTable report can contain sums, counts, and averages, while a Crosstab query cannot
(b)
We cannot create a PivotTable from a Crosstab query
(c)
A Crosstab query lets us group similar items, while a PivotTable query does not
(d)
None of the above
13. In Access 2010, the best types of queries to use for data analysis are: (a)
Select queries
(b)
Parameter queries
(c)
Action queries
(d)
All of the above
14. Which view allows adding tables to the query? (a)
Datasheet view
(b)
PivotTable view
(c)
PivotChart view
(d)
Design view
15. Which type of join in multi-table query permits to view all the records from one table and matching from another? (a)
Inner Join
(b)
Outer Join ADVANCED INFORMATION TECHNOLOGY TRAINING
67
DATABASE APPLICATIONS USING MS-ACCESS (c)
Equi Join
(d)
Non-Equi Join
16. For the database Apex Inventory Shipment, we need to present a graphical view of the sales volume of products. User should have the liberty to view all the products, or products from a particular category. For this purpose, a PivotChart is created. Which field should be placed in area Drop Series Fields Here? (a)
Category
(b)
Total Sales
(c)
Month
(d)
Item Number
17. For the above question, the area Drop Filter Fields Here should contain _________ field. (a)
Category
(b)
Item Number
(c)
Years
(d)
Month
18. To view the results in Datasheet view of the query created, do the following _____________. (a)
Press F5 key
(b)
Click Run on Design tab
(c)
Press CTRL + R
(d)
All of the above
19. The
option in Design ribbon permits us to create what type of queries?
(a)
Crosstab Queries
(b)
Action Queries
(c)
Parameter Queries
(d)
Group By Queries
20. For the database Apex Inventory Shipment, if we wish to delete all the invoices for which the payments were made in last quarter of year 2011, what should be done?
68
(a)
Create a select query and delete records manually
(b)
Create a sub-query with action query
(c)
Create simple action query
(d)
Cannot be done using queries
ADVANCED INFORMATION TECHNOLOGY TRAINING
CHAPTER
2
DESIGNING FORMS AND REPORTS
LEARNING OBJECTIVES Advanced Form Design Adding Unbound Controls Adding Graphics to Form Adding Calculated Values Adding Combo Boxes Make effective use of forms Displaying a calendar control on a form Organising information with tab pages Displaying a summary of data in a form Advanced Reports Creating customised headers and footers Adding calculated values Sub-reports Make Reports more effective Including a chart in a report Printing data in columns Cancelling the printing of a blank report
2.1. Introduction Forms help to display, add, modify, and delete data. Different features available in Access 2010 enable to create forms such that it becomes easier for the users to handle data. Access 2010 provides various methods to make forms handier and simpler. Different controls can be added to a form to enhance their working. Access also provides ActiveX controls which are Microsoft control meant for different purposes. A form can be divided into pages to increase the readability, or can include a summary section to display grouped data. Reports can be considered as the static version of forms. Reports are the best way to present data to higher authority and communicate the information to the people. They can be customized using header and footers, calculated values, and sub-reports to represent linked data. Access 2010 also provides the facility to create charts in reports which represents data diagrammatically. Since reports are used for business communication, it must be available for everyone.
DATABASE APPLICATIONS USING MS-ACCESS
2.2. Advanced Form Design Forms are an important medium of representing data in Access 2010. Forms are not only used for entering of data, but also to view the data in a user friendly manner. Access 2010 provides various controls and utility to make the forms more presentable. For example, forms can contain unbounded controls, graphics, calculated values, and combo boxes.
2.2.1 Adding Unbound Controls An Access 2010 Form can contain multiple controls, each having its own significance. These controls can be selected from Create tab in Forms ribbon. In general, all the controls are bounded to one field of the table or query the form is based on. However, there are few controls which retain the entered value, but are not linked with any table fields. These controls can be used for text label display, for controls such as lines and rectangles, or for holding unbound OLE objects (such as bitmap pictures or logo) that are not stored in a table, but in the form itself. Unbound controls are also known as variables or memory variables.
2.2.2 Problem Scenario The database Apex Inventory Shipment has a form frmOrders as shown in Fig. 2.2.1, based on table Sales Order which keeps track of all the orders placed. The Sales Manager wishes to add a current date on the form, so that it becomes easy for the user to keep track of dates.
Fig 2.2.1. frmOrders form Solution The Database Developer adds an unbounded control, a label to the form and sets its property to store the current date. Steps for adding an unbounded control 1. Right-click the form frmOrders under All Access Objects -> Forms tab. Select Design View from the dropdown to open the table in Design View, as shown in Fig. 2.2.2. 70
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig 2.2.2. Open the form frmOrders in Design view 2. Select the Date & Time control from Design ribbon ->Header/Footer tab. The Date and Time window appears, as shown in Fig. 2.2.3 select the date & time format from this window.
Fig. 2.2.3: Date and Time window ADVANCED INFORMATION TECHNOLOGY TRAINING
71
DATABASE APPLICATIONS USING MS-ACCESS 3. Click OK to close the window and draw the control on the Form Header portion on the form. The form should appear, as shown in Fig. 2.2.4.
Fig. 2.2.4: Date and Time unbounded control added to a form NOTE: In a same way, other controls like shapes, logo, etc. can be added to form. The properties of these controls can be set to meet user requirements.
2.2.3 Adding Graphics to Form Attractive forms are always a valuable addition. Access 2010 makes it easy to add a graphic to the background of a form, such as a “watermark” which appear on expensive bond paper. The picture can contain a company logo, text, or any other graphic element. The picture is specified by the form’s picture property and can be embedded in the form or linked to an external file. If the picture is linked, the graphic displayed on the form changes any time the external file is edited. The graphic can be inserted into the form in the following ways: 1. Import a graphic file (clip art, gif, jpeg, bmp, etc.) directly into the form. 2. Attach a link to the graphic that opens a website or other database object. 3. Associate the graphic with an existing macro in the database.
2.2.4 Problem Scenario Consider the frmOrders discussed in section 2.2.1. The Database Developer wants to make it more presentable and thought of adding a picture to the background of the form.
72
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS Solution The picture can be set as form background using the image control. Select the picture to be added, draw the image control and adjust its properties to make image as a background. Steps for adding graphics 1. Right-click the form frmOrders under All Access Objects -> Forms tab. Select Design View from the dropdown to open the table in Design View. 2. Select the insert image button from Design ribbon -> Controls tab and drag it to cover the Details section of the form. 3. The Insert Picture window appears. Browse for the picture to be inserted and click OK to close the window. The Insert Picture window is displayed in Fig. 2.2.5.
Fig. 2.2.5. Insert Picture window ADVANCED INFORMATION TECHNOLOGY TRAINING
73
DATABASE APPLICATIONS USING MS-ACCESS 4. The form after the picture is inserted appears, as shown in Fig. 2.2.6.
Fig. 2.2.6: Image inserted in form frmOrders 5. The picture is required to move to the back of controls. Right-click the picture and select Position -> Send to Back from the dropdown, as indicated in Fig. 2.2.7.
74
Fig. 2.2.7. Send the picture to back of controls ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS 6. The form appears, as shown in Fig. 2.2.8.
Fig. 2.2.8. Form with Graphics 7. Select the picture and press F4 to view its properties. In the property sheet, move to format and set the Size Mode property of picture to stretch, as shown in Fig 3.2.9.
Fig. 2.2.9. Set the image property 8. The final form appears, as in Fig. 2.2.10.
ADVANCED INFORMATION TECHNOLOGY TRAINING
75
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 2.2.10. frmOrders with Graphics inserted NOTE: While adding a graphic to the form, a link to that graphic can also be created. The link ensures that the changes made to original file are also reflected in form.
2.2.5 Adding Calculated Values Access 2010 provides many features to give forms enhanced behavior and a modern look. One of the major requirements in Access 2010form that it can be display computed results. These results may be bounded to some field in the table or may be unbounded. For example, we may need to display the complete name of the customer instead of displaying the first name and last name separately. Calculated controls can use any of the existing function or user build function available in Access 2010. Calculated values can also be expressions computed with a combination of other fields and operators.
2.2.6 Problem Scenario Consider the form frmOrders discussed in section 3.2.1. The Manager wishes to add another date in form, which may indicate when the order will reach customers. This date can be computed as 15 days after the date of shipment. Solution A textbox is added to the form.This textbox contains calculated value, which is computed as 15 days + date of shipment. Steps to add calculated values to form 1. Right-click the form frmOrders under All Access Objects -> Forms tab. Select Design View from the dropdown to open the table in Design View. 2. Select the textbox control from Design ribbon -> Controls tab and draw it on the details section of the form. The form should appear, as in Fig. 2.2.11. 76
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig. 2.2.11. Insert Textbox in Form 3. Double-click the label and type Delivery Date instead of Text25. Similarly, double-click the textbox and type =DateAdd("d",15,[Ship Date]). The form should appear, as shown in Fig. 2.2.12.
Fig. 2.2.12. Specify values for Textbox control ADVANCED INFORMATION TECHNOLOGY TRAINING
77
DATABASE APPLICATIONS USING MS-ACCESS NOTE: The formatting of the new added textbox can be copied from above cells. 4. Select Form View from Home ribbon -> Views tab to open the form in Form View. Confirm the textbox displays the calculated value.
2.2.7 Adding Combo Boxes Combo boxes in Access 2010 provide a way of selecting a value from a list. This is quicker than remembering which value to type and ensures that the entered value is valid. A combo box is a compact method of presenting a list of choices and allows user to enter a value that is not in the list. The values in a combo box are displayed by clicking the arrow at the end. In combo box values can be selected by clicking it or by typing the first few characters of the value into the text box area of the combo box. If the Auto Expand property is set to Yes, the default setting, Access 2010automatically fills in the rest of the value. Combo box consists of rows of data with one or more columns, which can appear with or without headings. One of the columns contains the values to be stored in the field (bound control) or use for other purposes (unbound control); the other columns contain explanatory information.
2.2.8 Problem Scenario Consider the form frmOrders created in section 3.2.1.Theexecutives are making many mistakes while typing the reference of the customer to which orders are sold. The Sales Manager asked the Database Developer to find the solution to this problem. Solution The Database Developer thought that it will be a good way to add a combo box for the customers. Users will have an option to choose the value from the list or type a new value if required, thereby decreasing the typing mistakes. Steps to add a combo box in Form 1. Right-click the form and select Design View from the dropdown to open the form in Design View. The form appears, as shown in Fig. 2.2.13.
78
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig. 2.2.13: frmOrders in Design View 2. Delete the Sale to Customer textbox. 3. Select the Combo Box control from Design ribbon -> Controls tab and draw it in the place of Sale to Customer textbox. The Combo Box wizard appears, as shown in Fig. 2.2.14.
Fig. 2.2.14. Combo Box wizard ADVANCED INFORMATION TECHNOLOGY TRAINING
79
DATABASE APPLICATIONS USING MS-ACCESS 4. Select the first option i.e. I want the combo box to look up the values in a table or query and click Next. 5. In the Select Table or Query window, select the table option from View tab and choose table Customer from the list, as indicated in Fig. 2.2.15. Click Next to continue.
Fig. 2.2.15. Select the required table 6. In the Select Field window, select field Customer Number from Available field and click on sign to put it into selected fields. Similarly, add First Name and Last Name to selected field. The window appears, as shown in Fig. 2.2.16. Alternatively, the user can double-click the fields to add them to selected field.
Fig. 2.2.16. Add field to Combo Box 80
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS NOTE: Even if the multiple fields are selected to be displayed in Combo Box, the Primary Key will be stored in table or form. 7. Click Next to continue. In the Sort Order window select Customer Number as 1. This is indicated in Fig. 2.2.17.
Fig. 2.2.17. Select Customer Number for Sort Order 8. In the Hide Key Column window, uncheck the Hide Key Column checkbox, as shown in Fig. 2.2.18. Click Next to proceed.
Fig. 2.2.18. Uncheck Hide Key Column Option ADVANCED INFORMATION TECHNOLOGY TRAINING
81
DATABASE APPLICATIONS USING MS-ACCESS NOTE: Hide Key Column hides the Primary Key to be displayed as a value in combo box, though internally only Primary key is stored. 9. The next window confirms a unique value to be stored in table. Select Customer Number and click Next, as indicated in Fig. 2.2.19.
Fig. 2.2.19. Select Field to be stored in Table 10. In the next window that appears, select the option Store the value in this field and select the value Sale to Customer from the dropdown, as indicated in Fig. 2.2.20. NOTE: The first option Remember the value for later use is used in case of unbound controls.
82
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig. 2.2.20. Select field to store the value 11. Click Next to make the Name window appear. Type the name cmbCustomers for the Combo Box and click Finish to close the wizard, as indicated in Fig. 2.2.21.
Fig. 2.2.21: Type Name for Combo Box 12. The Sale to Customer combo box appears on the form, as displayed in Fig. 2.2.22.
ADVANCED INFORMATION TECHNOLOGY TRAINING
83
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 2.2.22. Combo Box added in form 13. Set the formatting of the label and combo box to make it more presentable. Open the form in Form View to verify the added combo box. The form should appear, as shown in Fig. 2.2.23.
Fig. 2.2.23. The Combo Box List appears
2.3. Make effective use of Forms Most databases provide forms for data entry and for viewing data. Access 2010 provides few techniques that help enhancing the usability of forms, and in turn, the productivity of the users of database. Forms are used by most of the users on a regular basis, and hence it is very crucial to make the effective use of forms. Adding more capabilities to forms helps to save user time and work, and also present data in a more organised way. Some of the extended functionality of the form can be: 84
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Adding calendar control on a form
Organising information with tab pages
Displaying a summary with tab pages
2.3.1 Displaying a calendar control on a Form To make forms more presentable and user friendly, different types of controls can be added to forms. These controls can be as simple as controls that are available in the design ribbon -> controls tab, or can be a third party ActiveX control. ActiveX controls are usually graphical objects that do not operate as standalone solutions, and they run only in the Windows environment. Calendar control is one of the most popular ActiveX controls. While working with dates, it is always helpful to have a calendar nearby. If a form contains a date field, it is always good to add a calendar control which displays dates graphically and make the form more user-friendly. The calendar control provides properties that enable to set and retrieve dates in/from a table.
2.3.2 Problem Scenario Database Designer of Apex Ltd. has designed the frmOrders form to be used for Sales Orders table, as shown in Fig. 2.3.1 The Supervisor of the Customer Service Group informs the designer that the people taking orders often need to refer to a calendar to answer customer questions, such as when they will receive a shipment. A calendar is necessary so that the customer service employees can take weekends and holidays into account when they make an estimate as to when orders will be shipped.
Fig. 2.3.1. frmOrders Form Solution A Calendar control is added to all the date fields to make the form convenient for the users. The Database Developer adds a calendar control for Sales Date and Ship Date for users to pick up date graphically.
ADVANCED INFORMATION TECHNOLOGY TRAINING
85
DATABASE APPLICATIONS USING MS-ACCESS Steps to add a Calendar Control 1. Right-click the frmOrders and select Design View from the dropdown to open the form in Design View, as shown in Fig. 2.3.2.
Fig. 2.3.2. Open form frmOrders in Design View 2. From Design ribbon -> Controls tab, click the Insert ActiveX Control Command
.
3. The Insert ActiveX control window appears. SelectCalendar Control 11.0 from the list and click OK, as shown in Fig. 2.3.3.
86
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig. 2.3.3. Select Calendar control 4. The Calendar control is placed in the upper-left corner of the form. Drag it to the required position. The frmOrders after inserting the Calendar control appears, as displayed in Fig. 2.3.4.
ADVANCED INFORMATION TECHNOLOGY TRAINING
87
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 2.3.4: Calendar control inserted on the form 5. Select the Calendar control and press F4 to open the Property Sheet for the Calendar control 6. Move to the data tab in property sheet. Click the arrow next to the Control Source property, and choose Sales Date from the list, as shown in Fig. 2.3.5.
Fig. 2.3.5. Set the Control Source property 88
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS NOTE: The Calendar control has many properties that you can set to create a custom appearance. 7. To set other properties of Calendar control, click on Calendar properties appear, as shown in Fig. 2.3.6.
button in the Custom property in Other tab. The
Fig. 2.3.6. Calendar Properties
2.3.3 Organising information with Tab Pages A Tab control is an Access 2010control that allows user to create multiple pages in one form. Each page is separated by its own tab and becomes active when the user selects a tab. Tab controls are useful for presenting grouped information that can be assembled by category. A tab control has pages, each with a tab of its own. Each tab page can contain all types of controls, such as text boxes, combo boxes, images, and even command buttons.
2.3.4 Problem Scenario The Sales Manager asks the Information Analyst to store the information of the customer which could be displayed in a friendly manner, such that the customer’s personal details and company details can be viewed separately. Solution The Information Analyst advises the developer to divide the information into separate tab in a form. One tab in the form should contain customer contact detail, while the other can contain customer’s company details, and third tab can contain customer’s terms with the company. ADVANCED INFORMATION TECHNOLOGY TRAINING
89
DATABASE APPLICATIONS USING MS-ACCESS Steps to add tab in a form 1. On the Create ribbon -> Forms tab, click Blank Form to create a new form, as shown in Fig. 2.3.7.
Fig. 2.3.7: Open a blank Form 2. From the Field List window, open the plus sign with Customers table and drag the fields Customer Number, First Name, Middle Name and Last Name to the form. The form appears, as shown in Fig. 2.3.8.
Fig. 2.3.8. Add Fields to a blank form NOTE: If the field list window does not appear, click on Add Existing Field from Design ribbon -> Tools tab. 3. Click Home ribbon -> Views tab -> View and select Design View from the dropdown to open the form in Design View. The form appears in Design View, as shown in Fig. 2.3.9.
Fig. 2.3.9. Form in Design View 90
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS 4. Extend the size of the form as required. Click on tab control it into the form. The form appears, as shown in Fig. 2.3.10.
in Design ribbon -> Controls tab and draw
Fig. 2.3.10. Add tab control to a form 5. Double-click the tab Page28. Property sheet appears. Type the value Personal Details in Name property, as shown in Fig. 2.3.11.
Fig. 2.3.11. Change the name of first tab 6. In a similar manner, change the name of the second tab to Company Details. Right-click the Tab control and select Insert Page from the dropdown to add a new tab and change its name to Other Details. The form should appear, as in Fig. 2.3.12.
ADVANCED INFORMATION TECHNOLOGY TRAINING
91
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 2.3.12. Add three tabs to Form 7. Move to the Personal Details tab, and select the field Street, City, Country, Zip/Postal Code, Phone, Other Phone, and Email from the Field List window. The resultant form is displayed in Fig. 2.3.13.
Fig. 2.3.13: Add required field to personal Details tab 92
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS 8. In a similar manner, add the fields CompanyName, Company Details and Job Title to the Company Details tab and also the fields Credit Limit, Payment Terms, Comments, and Document submitted to the Other Details tab. 9. A tabbed form is prepared. Now the user can navigate between different tabs to view the information required. 10. Save the form as frmCutomers.
2.3.5 Displaying a Summary of Data in a Form Presenting a summary of data can be very useful to users who access database. PivotCharts and PivotTables are created in forms to display a summary of data. Pivot Table is used to summarize and analyzes data in a form. The idea of Pivot Table is to let users slice and dice the data in any way required at a given moment in time. Pivot Table represents the data in spreadsheet form, while Pivot Chart represents the same data in a graphical form. Both Pivot Chart and Pivot Table are different views of a form. Pivot Table represents the data in tabular form, in which one or more vales are represented in rows, another value in columns, and a summarized value at the intersection of row and column. Forms that lend themselves to be displayed in PivotTable or PivotChart view provide many ways for users to manipulate data. An example of such a form is one that contains information about country, city, salesperson, sales, and date of sale. Such form can be used to determine sales by city and salesperson for each month, or sales in each country for each salesperson during the year.
2.3.6 Problem Scenario The Sales Manager wishes to see the summarized data of sales. He requests the Database Developer to create a form in such a manner, that it should display the summarized data in terms of cost of Item Sold per year, per country. For example, he needs a report displaying summary of the items sold country wise and state wise in year 2008 Quarter-2. Solution The Database Developer first creates a query based on table Sales Order, Customers, Sales Item Description, and Inventory and fetches the required data from it. Once query is created, then a form using pivot table option is created over the query. Steps for creating a query 1. Open the Query Design window by clicking Create ribbon ->Queries tab -> Query Design. 2. Select the tables Customers, Sales Order, Sales Item Description and Inventory table from the Show Table window. Click OK to close the window. The Query Design window appears, as shown in Fig. 2.3.14.
ADVANCED INFORMATION TECHNOLOGY TRAINING
93
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 2.3.14. Query Design window 3. Select Country and State from the Customers table and drag them to the Add Columns tab. Similarly add the column Sales Date from Sales Order table and Item Number from Inventory table. Also add a calculated column as Total Sale: [Quantity] * [Price]. The resultant query window is displayed in Fig. 2.3.15.
Fig. 2.3.15. The query Design window 4. Save the query as SummarizedData and run to confirm the results. Steps for creating a Pivot Table Form 1. Select the query SummarizedData under All Access Objects -> Queries tab. From the Create ribbon -> Forms tab ->, click the dropdown arrow near More Forms and select Pivot Table from the list, as indicated in Fig. 2.3.16.
94
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig. 2.3.16. Select the Pivot Table option 2. The Pivot Table window appears along with the field list, as shown in Fig. 2.3.17.
Fig. 2.3.17. The Pivot Table window NOTE: If the Field List window does not appear, click Design ribbon -> Show/Hide tab and Field List. ADVANCED INFORMATION TECHNOLOGY TRAINING
95
DATABASE APPLICATIONS USING MS-ACCESS 3. Open the plus sign of the field Item Number and drag the field to Drop Row Fields Here. Open the plus sign of Country and State drag Country and then State to Drop Column Fields Here. Similarly, open the plus sign for Total Sale and drag the column Total Sale to Drop Totals or Detail Fields Here, and open the plus sign of Sales Date By Month and drag the fields Years and Quarters to Drop Filter Field Here. The resultant Pivot Table window is shown in Fig. 2.3.18.
Fig. 2.3.18. Pivot Table window 4.
96
Click the dropdown arrow of Sales Date by Month field. Deselect the Select All option and open the plus sign of year 2008, and select Qtr2 from the year 2008, as shown in Figure 2.3.19.
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig. 2.3.19. Select the required year 5. The Pivot Table window displays the sales made for each item country and state wise in Quarter2 of year 2008. NOTE: Pivot Table gives you a flexibility of selecting the desired data and view the data according to your requirements.
2.4. Advanced Reports Reports are one of the best ways to represent data. Reports can be made more advanced and more user friendly to represent the data in a more organized form. The Reports can include customized Headers and Footers such as to display the company Logo or the department. Also the calculated controls can be added to report to display computed values.
2.4.1 Creating Customised Headers and Footers Reports can include pairs of header and footer sections:
Report Header and Footer for printing information at the beginning and end of the report.
Page Header and Footer for printing information at the top and bottom of each page.
Group Header and Footer for printing information when the group starts or the group ends, if groups exist in the report.
To add a header/footer pair, right-click in the report design and choose Page Header/Footer or Report Header/ Footer from the shortcut menu. Page and report headers and footers are added as pairs, while In Group only Headers can be added.
ADVANCED INFORMATION TECHNOLOGY TRAINING
97
DATABASE APPLICATIONS USING MS-ACCESS Controls in the Report Header & Footer section are printed only once at the beginning and the end of the report. A common use of a Report Header section is as a cover page or a cover letter, or for presenting information that needs to be communicated only once to the user of the report. The Report Footer section can be used to display the summarized data of whole report, like author of report, date & time, etc. Controls in the Page Header & Footer section are normally printed at the top and bottom of every page. Typically, Page Headers serve as column headers in group/total reports; they can also contain a title for the report. A Group Header section normally displays the name of the group. Group Headers immediately precede Detail sections. A Group Header is added to the report if any grouping is done in the report. Each Header& Footer section in reports can be customized from their traditional look to meet user’s requirement. Different controls can be added to header and footer. The textboxes or labels can be used to display a user-defined message. Various functions and expression can be used to display summary results and computed data.
2.4.2 Problem Scenario The Database Developer has prepared a report rptCustomers to display all the details of the customers, as shown in Fig. 2.4.1. The Zonal Sales Head requires the report to be customized; each page of the report must contain the Report Title at the top and date & time at bottom.
Fig. 2.4.1: Report rptCustomers 98
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS Solution The Database Developer adds a Page Header & Footer to the report and customizes the Page Header to hold a label with Report Title, and Page Footer to contain the date & Time using Date Time control.
Steps to customize Page Header & Footer of the Report 1. Right-click the report rptCustomers under All Access Object -> Reports tab and select Design View from the dropdown to open the report in Design View. The Report Design View should appear, as in Fig. 2.4.2.
Fig. 2.4.2: Report rptCustomers Design view 2. Expand the Page Header section. Select a label control it on the Page Header section, as indicated in Fig. 2.4.3.
from Design ribbon -> Controls tab and draw
Fig. 2.4.3. Add Label to Page Header NOTE: If Report Header does not appear right-click the report and select Page Header /Footer to view them. 3. Type the text Customers into the label and format it according to the requirement, as shown in Fig. 2.4.4.
ADVANCED INFORMATION TECHNOLOGY TRAINING
99
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 2.4.4. Add Title to Label 4. In a similar manner, add a Textbox control to the Page Footer of the report from Design ribbon -> Controls tab. The resultant report appears, as shown in Fig. 2.4.5.
Fig. 2.4.5: Add Textbox to the Report 5. Delete the label of the Textbox and type =Now() in the textbox. The report appears, as shown in Fig. 2.4.6.
100
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig. 2.4.6. Add Textbox in Page Footer 6. Right-click the report and deselect Report Header/ Footer to remove the report header and footer. This is optional. The report header can contain some different text and can be displayed. 7. Open the report in Report View format by selecting Report View from Home ribbon -> Views tab to verify the data. The report should appear as in Fig. 2.4.7. Note that each page of the report contains the Report Title and Date/Time.
Fig. 2.4.7. Report View ADVANCED INFORMATION TECHNOLOGY TRAINING
101
DATABASE APPLICATIONS USING MS-ACCESS
2.4.3 Adding Calculated Values Reports in Access 2010 can be modified to display the data as per user requirements. In general, reports contain fields from the table, but many times it becomes necessary to add some computed values in reports. These computed values may count, sum, or calculate an average of the numeric values in a group created in the report. Also, these computed values can be calculated using one or more fields in a table, for example, to display the total cost by multiplying quantity and price. The calculated values in reports are added using a text box and specifying an expression. The liberty of displaying computed values helps to display the reports in a user-friendly format. The calculated values in the report can be displayed in two ways: using queries with calculated columns and creating reports based on them, or by computing values in the report itself using Expression and Functions. The calculated values in queries are displayed as fields in reports which use them.
2.4.4 Problem scenario Consider the report rptCustomers discussed in section 3.4.1.The Sales Head wishes the customer name should be displayed as a complete name, not as first name and last name. He requests the Database Developer to implement the change. Solution The Database Developer adds a calculated value that concatenates first name and last name in the report rptCustomers and replaces the First Name and Last Name textboxes. Steps to add Calculated Values 1. Right-click the report rptCustomers under All Access Objects -> Reports tab and select Design View from the dropdown. The report appears in Design View, as shown in Fig. 2.4.8.
Fig.2.4.8: report in Design View 2. Select the First Name and Last Name textboxes and delete them. Add a new Textbox control Design ribbon -> Controls tab.
from
3. Drag the Textbox in place of First Name and Last Name textboxes. The report should appear, as shown in Fig. 2.4.9. 102
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig. 2.4.9. Add Textbox control to Report 4. Delete the Textbox Label and type the text = [First Name] + “ “ + [Last Name] in the textbox. The report window appears, as shown in Fig. 2.4.10.
Fig. 2.4.10. Write the expression in calculated control 5.
Add a label control from Design ribbon -> Controls tab in the Page Header tab along with other headings. The Report should appear, as in Fig. 2.4.11.
Fig. 2.4.11. Add Label Control to Page Header ADVANCED INFORMATION TECHNOLOGY TRAINING
103
DATABASE APPLICATIONS USING MS-ACCESS 6. Type text Name in label and format the label accordingly. The Report should appear, as shown in Fig. 2.4.12.
Fig. 2.4.12: Format the label 7. Select Report View from Home ribbon -> Views tab to open the report in Report View. The resultant report should appear, as in Fig. 2.4.13.
Fig. 2.4.13. Report view
2.4.5 Sub-Reports Sub-Report is a report that is inserted in another report. A sub-report, a complete report in its own right, is inserted into another report, called the Main Report. Main Report can be either bound or unbound. A bound main report is based on a table or query and its sub-reports contain related information. An unbound main report is not based on a table or query, but can serve as a container for one or more sub-reports. A main report can include as many sub-reports as necessary. The sub-reports can be added to two hierarchy levels. 104
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS Sub-Reports are usually an extension of data in main report. For example, the main report can contain details about the sales in a year, while the sub-report can show data for sale of each item or charts and graphs summarising and illustrating the numbers in the main report. If a sub report is inserted in a bounded main report, it should contain some field to link to main report.
2.4.6 Problem Scenario Consider the Report rptCustomersdiscussed in section 3.4.1. The Regional Head notices that the database users face a big problem while tracing the orders placed by each customer. He asks the Database Developer to create a user-friendly object which can display both the customer’s details and orders placed by the customer. Solution The Database Developer decides to add a sub report to the report rptCustomers which include details of the orders placed by the customers. For this purpose, the table Sales Order is used and the fields Sale to Customer from Sales Order and Customer Number from Customers are mapped. Steps to add a Sub Report to Main Report
1. Right-click the report rptCustomers and select Design View from the dropdown to open the report in Design View.
2. In the Design View, expand the Details section. Select the sub-report control
from Design ribbon ->
Controls tab and draw the control in Details section.
3. The SubReport Wizard appears, as shown in Fig. 2.4.14.
Fig. 2.4.14. SubReport Wizard ADVANCED INFORMATION TECHNOLOGY TRAINING
105
DATABASE APPLICATIONS USING MS-ACCESS
4. Select the option Use Existing Tables and Queries and click Next to proceed further, as shown in Fig. 2.4.15.
Fig. 2.4.15. Select option to use existing table
5. In the Select Table or Query window, select the table Sales Orders from the list. Select the fields Sales Order Number, Sale to Customer, Sales Date, Ship Date from selected field to available field, as shown in Fig. 2.4.16.
Fig. 2.4.16. Select required Table 106
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
6. Click Next to advance. The Link Field window appears. Select Customer Number from Forms/Reports field and Sale to Customer from Subforms /Sub reports field. The Sub Report Wizard appears, as shown in Fig. 2.4.17.
Fig. 2.4.17. Link fields of main report and sub report
7. Click Next to proceed to Name of Sub report window. Provide a suitable name to your sub report, and click Finish to close the window as indicated in Fig. 2.4.18.
Fig. 2.4.18: Provide a name to the sub report. ADVANCED INFORMATION TECHNOLOGY TRAINING
107
DATABASE APPLICATIONS USING MS-ACCESS
8. Open the resultant report in Report View by selecting Report View from Home ribbon -> Views tab. Final report appears, as shown in Figure 2.4.19.
Fig. 2.4.19. Customers and Orders placed by them
2.5. Make Reports more effective Reports are a way of communicating database information. By customizing reports, the information can be presented in the most effective format. A customized report developed by using Access 2010 tools can reach a wider audience and enable more users to handle them. Different methods to make reports effective can be:
including charts in a report
printing data in columns
canceling the printing of a blank report
creating report snapshot
2.5.1 Including a Chart in a Report Chart is a graphical representation of information used to illustrate quantitative relationships. It is a diagram that depicts a relationship, often functional, between two sets of numbers or between a set of numbers and a set of categories. Microsoft Graph is used to chart data from any of the database tables or data stored within other applications. It creates graphs in a wide variety of styles, such as bar graphs, pie charts, line charts, and others. Because Microsoft Graph is an embedded OLE application, it does not work by itself. As such, it has to be run from within Access 2010. In other words, it is dependent on Access 2010. 108
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS Different Chart Types Chart Type
Purpose
Column Chart
Used to compare multiple values of categories or differences over a period of time. The horizontal axis depicts categories and the vertical axis depicts values.
Bar Chart Area Chart
Used for the same purposes as a Column Chart. However, the horizontal axis of a Bar Chart shows values and the vertical axis shows categories or periods of time. Used to emphasize differences in individual values to the total, over a period of time.
Line Chart
Used to compare trends over a period of time.
Pie Chart
Used to show the relationship of a part to the whole. It is suitable for depicting one data series or data at a point in time.
Charts can be included in reports to illustrate the information more clearly. Charts enhance the data presented in reports by summarising the information and illustrating it in easily understandable ways. The reader can analyse trends and make comparisons using charting tools. The chart can be linked to a field in the underlying table or query.
2.5.2 Problem Scenario The Sales Head wishes to create a summary report. The report should show the quarterly total sales for each category. The Sales Head requests the Information Analyst to show a diagrammatic representation of the report. Solution The best way to display the summary report is to create charts to represent the data. The charts can be included in a report, and based on a query to show its diagrammatic representation. Steps to Include Chart in Report 1. The Query Sales data represents the summarized data for per quarter sale. The design of the query is displayed in Fig. 2.5.1.
ADVANCED INFORMATION TECHNOLOGY TRAINING
109
DATABASE APPLICATIONS USING MS-ACCESS
Fig. 2.5.1. Sales Data Query 2. Select Report Design from Create ribbon -> Reports tab. A blank report opens. 3. Select Chart control from Design ribbon -> Controls tab and draw it on the report. The Chart Wizard appears, as shown in Fig. 2.5.2.
Fig. 2.5.2. Chat Wizard 110
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS 4. Select the Queries option, and select Query: Sales Data from the list, as indicated in Fig. 2.5.3.
Fig. 2.5.3. Select Queries Sales Data 5. Click Next to advance. The Select Field window appears. Select all the fields: Category, Qtr, and Sales, as shown in Fig. 2.5.4.
Fig. 2.5.4. Select required fields ADVANCED INFORMATION TECHNOLOGY TRAINING
111
DATABASE APPLICATIONS USING MS-ACCESS 6. Click Next to proceed. In the Choose Chart Type, select the Column Chart
and click Next.
7. In Preview Chart window drag field Qtr to Axis, Category to Series and Sales to Data as shown in Fig. 2.5.5. Click Next to advance.
Fig. 2.5.5. Drag the fields to chart 8. Specify the title for the chart and select the Display Legend option. Click Finish to close the window. 9. The resultant chart appears, as shown in Fig. 2.5.6.
Fig. 2.5.6. The Sales Data Report 112
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS NOTE: The chart object can be modified by right-clicking and selecting Chart Object -> Edit from the dropdown. Also, the chart object can be embedded with existing data in the report so that the chart changes with each record display.
2.5.3 Printing Data in Columns Reports are a handy tool to represent data. The visibility of the reports makes an impact on how data can be viewed. Some of the reports may involve long lists of just a few fields of data—such as a phone or product list. These may be best arranged in multiple columns for better readability. While working with many databases, it is natural to come across some that consists of long lists of information. As a result, printing such data can mean printing a single column on many pages. The multiple columns for the report can be set using the Report Page Setup property and setting the number of columns to 2 or more, as shown in Fig. 2.5.7.
Fig. 2.5.7. Select multiple columns from Page Setup
2.5.4 Cancelling the Printing of a Blank Report If a report contains no records, the detail area of the report will be blank. While printing reports, it is not be advisable to print blank report. Macros can be used to cancel printing of a blank report and thus save time and effort. Depending on the availability of data, certain records may be absent in a report and printing a blank report would be meaningless.
ADVANCED INFORMATION TECHNOLOGY TRAINING
113
DATABASE APPLICATIONS USING MS-ACCESS To cancel previewing or printing of a blank report when the underlying query has been run with no records returned, the On No Data event of the report is used.
2.5.5 Problem scenario The Database Developer has prepared a report CustOrders, which accepts the customer’sfirst name and displays all orders placed by the customer in the current quarter. However, most users while printing the report found that the even when the query returns no results, the report is printed. They requested the Database Developer to resolve the problem. Solution The report event On No Data can be used to cancel the printing of report when no data is returned. Steps for Canceling the Print 1. Open the CustOrders Report in Design View. 2. Press F4 to open the property sheet of report. Make sure that the report is selected in the Selection Type textbox. On the Event tab, select the property On No Data, as indicated in Fig. 2.5.8.
Fig. 2.5.8. Property Sheet of Report 3. Select button of On No Data property.Choose Builder window appears. Select Macro Builder and click OK as shown in Fig. 2.5.9.
114
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
Fig. 2.5.9. Open Macro Builder 4. In the Macro Builder window, select Action MsgBox and specify the value of message Arguments as No Records Found, Title as Customers Orders, as indicated in Fig. 2.5.10.
Fig. 2.5.10. Specify MsgBox Action ADVANCED INFORMATION TECHNOLOGY TRAINING
115
DATABASE APPLICATIONS USING MS-ACCESS 4. Specify the second action as CancelEvent and click the Close button to close the Macro window. The confirmation message appears, as indicated in Fig. 2.5.11.
Fig. 2.5.11. Confirm to close the macro 5. Click Yes to save the macro and close the message window. The macro now appears on No Data event. 6. Open the report and verify that the macro is working.
2.6. Summary Forms and Reports are a crucial part of data representation in Access 2010. Access 2010 provides various utilities to make Forms and Reports more user-friendly and presentable. Different controls can be added to forms to display the logo of the company, date and time, and pictures. Forms also permit the inclusion calculated values and combo boxes which make it much easier to handle the controls and present data to user. This control helps make data handling easier for the user. Access 2010 provides various ActiveX like calendar control to make forms more interactive. Sometimes, it is required to display the information on a form in groups. The tab control available with Access 2010 can be used for this purpose. The popular utility for summarizing data of Pivot Table to summarize data is also available in Access 2010. Reports represent static data, but are a useful way of communicating. Reports in Access 2010 can be customized to user’s requirements including its header and footers. Another crucial feature available with reports is sub-reports, which enable data linking in several tables. Apart from this, we can add charts and calculated controls to reports to make them more visible. The properties of reports can be used to avoid printing of blank reports.
Lab Exercises Considering the Apex Inventory Shipment database of Apex Ltd. Provide a solution to the following problem scenarios:
1. The Sales Manager of the company has demanded a form displaying the details of the orders, containing with Items ordered, Shipping Details and Invoice Information. Design the form Order Details as displayed in Figure below. Create tabs to represent the data.
116
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
On the Order Details Form created in Question1 implement the Question 2 to 7:
2. In the Order Details form, convert the Customer Textbox to Combo Box which contains Customer Number and Company Name.
3. To make the Order Details form more user-friendly, add a calendar control to the form to select the Order Date.
4. The Sales Manager asked the developer to add a logo of the company the Order Details form as the form will be circulated among all divisions.
5. The database developer needs to make the form more presentable and has to add a picture on the background of each tab. Implement the needful.
6. In the Order Details tab of the form, add a calculated value that calculates the Total Price as Qty * Unit Price – Discount as shown in Figure below:
ADVANCED INFORMATION TECHNOLOGY TRAINING
117
DATABASE APPLICATIONS USING MS-ACCESS
7. The Sales Manager of the Company wishes to launch some sales promotional offers. He requested the database developer to create a form which should display the summarized count and cost of Orders placed by each customer on Quarter and month basis. He should also be able to view the same results for a particular category. Create a form containing Summary of Data. The developer of Apex Inventory Shipment database needs to create Item Sales report. The report should be grouped by Category and then Item and should display quantity and price of Item sold. The report is displayed in Figure below:
Implement the Questions 8 – 14 based on the report Item Sales.
8. Add a calculated control Total Sales on the report that should display the Total Sales as Price * Quantity. 9. Add a Page Header and Footer on the Report. The header must contain the logo of the company and Footer must contain the current Quarter and Month.
10. Compute the Total Sales for each product in group footer. 11. Include a pie chart in the Category group footer that should display the ratio of sales of each product in that category. The report should look like as in Figure below:
118
ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
12. The details of the Sales of Item were to be presented in the Monthly meeting as a hardcopy. So the Manager asked the executive to get the report into columnar format so that is more readable. Remove the Page Headers and the chart, and print the report in two columns.
13. For the Annual review of the sales, the Vice President demanded a report displaying the product sales by month. The reports should display the products from a particular category, which is given by the user. The report should represent the data diagrammatically using charts. Create the required Report.
14. The Sales Manager found that there are few categories which are not produced any more by the company but are not discarded in the report. As a result if such category is entered, a blank report gets printed. As a report administrator, cancel the printing of the blank report. Multiple Choice Questions
1. The controls that are not linked to any field of the table or query on the form are known as ________. (a)
ActiveX control
(b)
Unbounded Controls
(c)
Graphics Control
(d)
Bound Controls
2. The Vice President of the Company wishes to add the image of the company vision statement as a background of all the forms. Which control can be used for the purpose?
(a)
Calendar Control ADVANCED INFORMATION TECHNOLOGY TRAINING
119
DATABASE APPLICATIONS USING MS-ACCESS
(b)
ActiveX control
(c)
Image Control
(d)
Graphics Control
3. Which of the Header in reports can be viewed separately from the Footer? (a)
Page Header
(b)
Group Header
(c)
Report Header
(d)
All of the above
4. The Manager requested the developer to create a Inventory form in a manner such that the Product’s description is stored in one group, the cost and supplier information another group. Which is the best control to display the required information?
(a)
Use the Tab Control
(b)
Use SubForms
(c)
Add ActiveX Control
(d)
None of the above
5. Which property of the form can be used to insert a background image? (a)
Caption
(b)
Background
(c)
Record Source
(d)
Picture
6. The Sales Executive while filling the details of the orders placed find it very difficult to type the name of each product every time it is ordered. They demanded that the form should provide them a drop down to select the product to be ordered. How can we implement the required?
(a)
Using the query in the form
(b)
Using the Combo Box control
(c)
Using a SubForm
(d)
Cannot be done
7. The Calendar control can be selected from _______________
120
(a)
Microsoft Office-> Access Options
(b)
Design -> Controls
(c)
Design -> Controls -> ActiveX controls
(d)
Create -> Forms ADVANCED INFORMATION TECHNOLOGY TRAINING
DESIGNING FORMS AND REPORTS
8. The Regional Sales Head demanded a summary report indicating the monthly sales done by each employee in each zone. Which kind of form is best to display the required data?
(a)
Use tabbed browsing
(b)
Insert an Image in form
(c)
Insert SubForm
(d)
Create Pivot Table
9. To print the multi-columnar report, the number of columns can be set through _________ property. (a)
Report property sheet
(b)
Page Setup
(c)
Report wizard
(d)
Grouping
10. The persons from the delivery team found it very annoying that even when the reports contained no data, they are printed and they have to search for such reports among all the printed data. They requested the developer to find the solution to this problem. Which property of report can be used to implement the requirement?
(a)
CancelPrint
(b)
CancelEvent
(c)
Create a macro called On No Data
(d)
Create a macro called On Print
11. To display the data of the Products and the orders placed for each product in the current month. The following feature available in Reports can be used.
(a)
Report Wizard
(b)
Nested Reports
(c)
Grouping
(d)
SubReports
12. The Regional Head wishes to view the diagrammatic representation of data indicating the sales made by each zone in his region. Which feature can help to implement the requirement?
(a)
Graphics
(b)
ActiveX
(c)
Charts
(d)
Pivot Table
13. To display the list of employees grouped according to first letter of their name, which type of controls can be used in reports? ADVANCED INFORMATION TECHNOLOGY TRAINING
121
DATABASE APPLICATIONS USING MS-ACCESS
(a) (b) (c) (d)
Use Calculated values in group Add grouping control Add Function control Add ActiveX control
14. Which property of the control is used to bind it to a field of a table or a query? (a) Data (b) Record Source (c) Field (d) None of the above 15. Each tab in a tab control is known as _________. (a) Page (b) Data Tab (c) Control Page (d) Control 16. The Sales Manager requested a summary form which should enable him to choose the category and display the monthly sale of each product in the category. In the created Pivot Table Form, The category field should be placed in which area?
(a) (b) (c) (d)
Drop Row Fields Here Drop Column Fields Here Drop Totals or Detail Fields Here Drop Filter Field Here
17. A developer created a report displaying the information of customer grouped according to country and state. To add a count of customer in each state the count textbox should be placed in which section of the report?
(a) (b) (c) (d)
Page Footer Report Footer State Group Footer Country Group Footer
18. The SubReport in the main report can be inserted to _______________ hierarchy level? (a) 7 (b) 3 (c) 2 (d) 4 122
ADVANCED INFORMATION TECHNOLOGY TRAINING
CHAPTER
3
BUILDING CRITERIA EXPRESSIONS
LEARNING OBJECTIVES Using operands in Criteria Expressions Using built-in functions Working with Expression Builder
3.1 Introduction Expressions in Microsoft Access 2010 can be considered similar to formulae in Microsoft Excel. Expressions are a combination of operands, operators, functions, and values that are evaluated according to their order of precedence. Expressions can be used with tables, queries, forms, reports, and macros. In Access, expressions are used to obtain calculated values, provide criteria, and query or supply constraint to table columns. Access also provides a powerful user interactive graphical tool to create expressions known as Expression Builder. In this chapter, we will discuss how to build criteria expressions in Access. We will also look at using various components of an expression for building query criteria. This chapter will also identify various operators available in Access 2010. Next, we will discuss the available built-in functions in Access. We will discuss the different type of functions and their utilisation. Further, this chapter will cover how to use Expression Builder to create expressions using Objects, Functions, Operators, and Identifiers.
3.2. Using Operands in Criteria Expressions Query criteria are the most important part of any query as they permit users to select only the desired records from an existing table. An operand is a value on which a calculation is performed. In other words, an operand is a data value that gets manipulated in the query expression. Operands can be literals, identifiers, or functions.
3.2.1 Literals A literal is value that is not addressed by any name. It can be typed directly into the criteria expression. In Access, literal can be of type number, text, date, or logical value (i.e. True or False). Literals are also referred as constants as their values remain static throughout the evaluation of expression. Examples of literal: “Hello” + “ “ + “Everyone” , Here Hello and Everyone are Text literals [Date] > #1/1/2011#, Here 1/1/2011 (1-Jan-2011) is a Date literal
DATABASE APPLICATION USING MS-ACCESS
3.2.2 Identifiers Identifiers are variables. In Access, identifiers represent field name, table name, or control name. Identifiers are a crucial part of expression building as they specify the column to which an expression represents. While creating an expression in Access, identifiers are always represented in square brackets [ ]. Examples of identifiers used in an expression: [Basic Salary] + [Tax]: Where Basic Salary and Tax are identifiers
3.2.3 Functions Functions provide specialised operations to enhance the working of Access. Functions are built-in expressions that take an input, perform necessary calculations on it, and return the output. The input accepted by the function is called arguments; a function may have one or more number of arguments. Access provides us different functions to work with different type of data, such as Text functions, Date and Time functions, Numeric functions, and Mathematical functions. For example, a text function Length takes an input string as an argument and returns the length of the string in number as: Length (“MS Access”) will return 9. Problem Scenario Apex Ltd. is launching a new production unit in “California”, which will also focus on some new products. To promote these products a detailed list of all existing customers from “California” (state code CA) is required. Solution To achieve this, a query displaying Name, Contact Info, and Address of the customers is required. To get only the customers from “California”, the value CA in the criteria for the state field needs to be specified. Here, CA is a literal operand and is typed direct in query criteria. Steps for creating required query 1.
Click Create ribbon -> Other -> Query Design to open the Query Design window.
2.
Select Customers from Show Table and click Add, as displayed in Fig. 3.2.1.
124
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS
Fig. 3.2.1. Show Table window 3.
Select the columns Salutation, First Name, Middle Name, Last Name, Company, Street City, State, Zip/Postal Code Phone, and Email from table Customers and drag them to the columns tab. The Query window appears, as shown in Fig. 3.2.2.
Fig. 3.2.2. Select Required Columns ADVANCED INFORMATION TECHNOLOGY TRAINING
125
DATABASE APPLICATION USING MS-ACCESS Now, we will add criteria to get records from “California”. 4.
In the Criteria tab of field State, write the literal “CA”, as indicated in Fig. 3.2.3.
Fig. 3.2.3. Specify criteria for State 5.
Click Save
in the toolbar to save the query. Type the name of query as “Customers from California”.
6.
Click the Run sign
in Design ribbon -> Results to view the results of the query, as shown in Fig. 3.2.4.
NOTE: Literals are usually combined with operators to form complex expressions for query criteria.
Fig. 3.2.4. Query Results 126
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS
3.3 Using Operators in Criteria Expressions Operators make the expression complete. They are special symbols, such as +, -, used with operands to perform calculations. Every operator has a specific meaning and a symbol. Operators help create expressions with the combination of identifiers and values. Every operator is executed according to its priority. For example: In [BasicSalary] + [Tax], “+” is an operator. Different types of operators are:
Comparison operators
Arithmetic operators
Miscellaneous operators
Compound criteria and logical operators
3.3.1 Comparison Operators Comparison operators, also known as relational operators, define relation between two identifiers or two values by comparing them. These operators can be used with Numeric or Date data type. Comparison Operators are listed in Table 3.1 OPERATOR
NAME
EXPLAINATION
>
Greater Than
Num1 > Num2 returns true if Num1 is greater than Num2
<
Less Than
Num1 < Num2 returns true if Num1 is less than Num2
>=
Greater Than Equal to
Num1 >= Num2 returns true if Num1 is greater than or Equal to Num2
<=
Less Than Equal To
Num1 <= Num2 returns true if Num1 is less than or equal to Num2
<>
Not Equal To
Num1 <> Num2 returns true if Num1 is not equal to Num2
=
Equal To
Num1 = Num2 returns true if Num1 is equal to Num2 Table 3.1: Comparison Operators
3.3.2 Arithmetic Operators Arithmetic operators, commonly known as mathematical operators, are used with numeric data to perform calculations.
ADVANCED INFORMATION TECHNOLOGY TRAINING
127
DATABASE APPLICATION USING MS-ACCESS Arithmetic Operators are displayed in Table 3.2. OPERATOR
NAME
EXPLAINATION
+
Addition
-
Subtraction
*
Multiplication
/
Divide
Returns integer as a result of division of integer numbers and decimal as a result of division of decimal numbers, that is, 5\2 will return 2.5 and 5\2.5 will return 2.
\
Integer Divide
Returns integer as a result of division, that is, 5\2 will return 2 and 5\2.5 will return 2.
^
Exponentiation
Computes power, that is, the result of 5^3 is 125.
Mod
Modulo
Returns the remainder of the division of two integers, that is, 5/2 will return 1. Table 3.2: Arithmetic Operator
3.3.3 Miscellaneous operators In Access, a special set of operators is used with multiple data types. These operators provide an additional functionality to create expressions. Some of the miscellaneous operators are – LIKE, Between, IN, Is Null etc. 3.3.3.1 The LIKE Operator The LIKE operator works with text or date data type. LIKE is used to match text patterns in the query criteria. This operator uses various wildcards to form different patterns. The various wildcards that can be used with LIKE are mentioned in Table 3.3. Wildcard
Explanation
Example
*
Denotes any number characters (0 or more)
?
Denotes a single character
LIKE ‘B??K’ will match all the text with B as first letter, k as last letter and 2 letters in between. For example- Book, Back
#
Denotes a single digit
LIKE ‘#ABC’ will match text which starts from a digit followed by ABC.
[xyz]
Denotes a set of characters
LIKE [ABC]* will match all text starting from either A, B, or C.
of
LIKE ‘A*’ will match all the characters starting from A For example, Accounts, Audit
Table 3.3: Wildcards with LIKE operators 128
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS 3.3.3.2 The Between… And Operator The Between operator is used with Numeric and Date data type to obtain a set of values within a specified range of values. For Example: Between 10 and 20 will give all the values within the range of 10 and 20 including 10 and 20. Between #1/1/2011# And #8/1/2011# will return all the dates between 1-Jan-2011 And 1-Aug-2011. (Note that dates are included between # and are written in “mm/dd/yyyy” format). 3.3.3.3 The IN operator The IN operator is used to match a value to a set of values given. This operator can be used with Numeric, Text, or Date data types. For Example: [Month] IN (‘Jan’, ‘Feb’, ‘Apr’, ‘May’) will match all the month values which are either from the specified values. 3.3.3.4 The IS NULL operator The IS NULL operator is used to find the null records in table. We use IS with NULL to indicate all the record which are null in the table. Note: Null is not “0” or “blank”. For Example: [Discount] IS NULL will return all the records with [Discount] value as NULL. Similar to IS NULL, IS NOT NULL searches for non-null values. For Example: [Advance Amount] IS NOT NULL will return all records where [Advance Amount] is not null.
3.3.4 The Logical Operators A logical operator results in expression that returns True or False. These operators are used to combine multiple expressions. They are also known as Boolean operators. The logical operators are listed in Table 3.4. OPERATOR
NAME
EXPLAINATION
And
Logical And
Returns True if both the expressions compared are True
Or
Logical Or
Returns True if either of the expressions compared is True
Eqv
Logical Exclusive Nor
Xor
Logical Exclusive Or
Return True if either both the expressions are True or both the expressions are False Return True if either of the expressions is True
Not
Logical Not
Works with a single expression and returns True if the expression is False Table 3.4: List of Logical Operators
ADVANCED INFORMATION TECHNOLOGY TRAINING
129
DATABASE APPLICATION USING MS-ACCESS
3.3.5 Understanding the Operator Precedence Access permits to create complex expressions containing multiple operators. To evaluate these expressions, Access determines which operator to evaluated first, and then which is next, and so forth according to a predetermined order. This order is known as operator precedence. Every operator is assigned a precedence order and is calculated in the same order. The only exception to this rule is parenthesis (). Parentheses are used to group expressions and override the default order of precedence. Operations within parentheses are performed before any operations outside them. Within the parenthesis all operators are computed on basis of their precedence. Operator precedence is similar to BODMAS order that is followed in algebra. Parenthesis or brackets over here perform the same function to change the priority order of operators. Note: BODMAS = B
Brackets first
O
Orders (ie Powers and Square Roots, etc.)
DM
Division and Multiplication (left-to-right)
AS
Addition and Subtraction (left-to-right)
Operators are first preceded in the order of their category and then within each category each operator has its own precedence order. Operators precedence according to their category is displayed in Table 3.5, from the highest to the lowest. OPERATOR CATEGORY
PRECEDENCE ORDER
Arithmetic
I
Comparison
II
Boolean
III
Table 3.5: Operator Precedence according to Category Table 3.6 displays precedence of each operator within different categories from the highest to the lowest. CATEGORY
OPERATOR
SYMBOL
PRECEDENCE ORDER
Exponentiation
^
I
Multiplication and/or division (left to right)
*,/
II
Integer division
\
III
Modulo
Mod
IV
Addition and/or subtraction (left to right)
+, -
V
Arithmetic
130
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS
Comparison Equal
=
I
Not equal
<>
II
Less than
<
III
Greater than
>
IV
Less than or equal to
<=
V
Greater than or equal to
>=
VI
Logical Not
I
And
II
Or
III
Xor
IV
Eqv
V
Imp
VI Table 3.6: Operator Precedence within Category
3.3.6 Using Compound Criteria Queries can help retrieve data in any form. Queries are usually created on multiple criteria, known as compound criteria. There are two types of compound criteria - “AND” and “OR.” 3.3.6.1 AND Criterion In AND, compound criteria will return results only if each individual criterion is true. For example, if we add criteria to the query from the Customer table as: [State] = “CA” AND [Credit Limit] > 500000, it will return customers from California who have credit limit greater than 500000. The AND criteria in a query designer is specified by writing all the criteria in some row of the Criteria tab, as shown in Fig.3.3.1.
ADVANCED INFORMATION TECHNOLOGY TRAINING
131
DATABASE APPLICATION USING MS-ACCESS
Fig. 3.3.1. Specifying AND compound criteria 3.3.6.2 OR Criteria The OR compound criteria are used in queries where we need to match either of the criterion specified in query criteria. OR returns result even if any criterion is true. For example, if we add criteria to the query from the Customer table as: [State] = “CA” OR [Credit Limit] > 500000, it will return all customers who are either from California or who have credit limit greater than 500000. The OR criteria in a query designer is specified by writing all the criteria in different rows of the Criteria tab, as shown in Fig. 3.3.2.
132
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS
Fig. 3.3.2: Specifying OR Compound Criteria
ADVANCED INFORMATION TECHNOLOGY TRAINING
133
DATABASE APPLICATION USING MS-ACCESS Problem Scenario This case study focuses on the operators discussed above and how to use them as a Criteria Expression. At the end of a quarter, Country Head of Apex Ltd. wishes to review the following data:
A report displaying all sales orders placed in from January to March 2008.
All inventory details from the “Car”, “Snowmobile”, and “Boat” categories along with the details of the order placed for them.
A list of all the products that were sold with a quantity greater than 5, or the price greater than 1000.
A contact list for all Customers whose first name starts with A, B, or C.
Solution For creating the query containing the report of Sales Order, the query will be created on the Sales Order table, using “Between” and ”And” operator in query criteria. The inventory details query will contain the Inventory table and Sales Item Description. The query criteria will be based on the IN operator. For obtaining the list of products, query needs to be based on Inventory and Sales Item Description containing compound criteria. To retrieve the contact list of Customers, query will be based on the Customers table and the criteria for the first name will contain the LIKE operator. Steps for creating query containing the report of Sales Order 1.
Click Create ribbon -> Queries -> Query Design to open the Query Design window.
2.
Select the Sales Order table from the Show Table window and click Add, as shown in Fig. 3.3.3.
Fig. 3.3.3. Show Table window 134
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS Select all the columns from the Sales Order table and drag them to the Columns tab. The Query window appears, as shown in Fig. 3.3.4.
Fig. 3.3.4. Select Required Columns 3.
In the Criteria section of the Sales Date column, write the criteria BETWEEN 1/1/2008 AND 3/31/2008. Set the Sort order of column as Ascending, as shown in Fig. 3.3.5. NOTE: The Query Builder window formats the date with # sign.
Fig. 3.3.5. Specify Query Criteria ADVANCED INFORMATION TECHNOLOGY TRAINING
135
DATABASE APPLICATION USING MS-ACCESS 4.
Click the Run sign
in Design ribbon -> Results to view results, as shown in Fig. 3.3.6.
Fig. 3.3.6. Query Result 5.
Click
on the toolbar to save the query. Type the name of query as “Sales Order QTR1”.
Steps for creating inventory details query 1.
Click Create ribbon -> Queries -> Query Design to open the Query Design window.
2.
Select the Inventory and Sales Item Description table from the Show Table window and click Add, as shown in Fig. 3.3.7.
Fig. 3.3.7: Show Table Window 136
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS 3.
Select Item Number, Category, Sub Category, Description, and Model from the Inventory table and drag them to the Columns tab. Similarly drag Sales Order Number, Quantity, Unit, and Price. The Query window appears, as shown in Fig. 3.3.8.
Fig. 3.3.8: Specify Required Fields 4.
In the Criteria section of the Category column write the criteria IN (Car, Snowmobile, Boat), as shown in Fig. 3.3.9.
Fig. 3.3.9: Specify Criteria for Column ADVANCED INFORMATION TECHNOLOGY TRAINING
137
DATABASE APPLICATION USING MS-ACCESS 5.
Click
on the toolbar to save the query. Type the name of query as “Inventory Sales”.
Steps for creating the query to obtain the list of products 1.
Click Create ribbon -> Queries -> Query Design to open the Query Design window.
2.
Select the Inventory and Sales Item Description table from the Show Table window and click Add.
3.
Select Item Number, Category, Sub Category, Description, and Model from the Inventory table and drag them to the Columns tab. Similarly, drag Sales Order Number, Quantity, and Price. The Query window appears, as shown in Fig. 3.3.10.
Fig. 3.3.10. Specify Required Columns 4.
In the Criteria section of the Quantity column write the criteria > 5. In the next row, write the criteria for Price as > 1000. The Query design window should appear as shown in Fig. 3.3.11. NOTE: Since this is an OR compound criteria, both the criteria are written in different rows.
138
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS
Fig. 3.3.11. Specify Compound Criteria 5.
Click
6.
Click
on the toolbar to save the query. Type the name of query as “Inventory Sales – Qty Price”. in Design ribbon -> Results to view the results, as shown in Fig. 3.3.12.
Fig. 3.3.12. Query Results ADVANCED INFORMATION TECHNOLOGY TRAINING
139
DATABASE APPLICATION USING MS-ACCESS Steps for creating query to retrieve the contact list of Customers 1.
Click Create ribbon -> Queries -> Query Design to open the Query Design window.
2.
Select the Customers table from the Show Table window and click Add.
3.
Select Customer Number, First Name, Last Name, Company, City, State, Country, and Phone from Customers and drag them to the Columns tab. The Query window appears, as shown in Fig. 3.3.13.
Fig. 3.3.13. Specify Require Fields 4.
140
In the Criteria section of the First Name column write the criteria LIKE “[ABC]*”. The wildcard [ABC]* with operator LIKE specifies that it should match any string starting from A, B, or C. Also set the sort order of the First Name field to Ascending. The Query Design window should appear as shown in Fig. 3.3.14.
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS
Fig. 3.3.14. Specify Query Criteria 5.
Click
6.
Click
on the toolbar to save the query. Type the name of query as “Customers Contact List – ABC”. in Design ribbon -> Results to view the results, as shown in Fig. 3.3.15.
Fig. 3.3.15. Query Results Many complex Criteria Expressions for a query can be created using the combination of operators and operands. Combining multiple criteria and different operators can help get the required data.
3.4 Using the Built-In Functions Built-In Functions provide specialized operations to enhance the working of Access. We can perform mathematical, financial, comparative, and other operations using functions. ADVANCED INFORMATION TECHNOLOGY TRAINING 141
DATABASE APPLICATION USING MS-ACCESS Some useful types of functions available in Access are:
Mathematical
Date/Time
Financial
SQL Aggregate
Text
3.4.1 Using Text Functions Text functions are used to perform various operations on strings, such as manipulating strings, concatenate the string, extracting a portion of string. Some useful string functions are listed in Table 3.7. FUNCTION NAME Left() Right() Mid()
Len() Lcase() Ucase() Instr()
Trim() Replace() Strcomp()
StrReverse()
EXPLAINATION Returns specified number of characters from left of the string Returns specified number of characters from right of the string Returns specified number of characters from the given position in string Returns the length of the given string Converts the text to lower case Converts the text to capital case Returns the position of first occurrence of a string in another string Removes leading or trailing spaces in a text Converts a substring from the given string into specified string Compares two strings Returns 0 if strings are same. 1 if first string is greater the second. -1 If first string is less than the second. Returns the string in reverse order
EXAMPLE Left(“Access”,3) will return Acc Right(“Access”,3) will return ess Mid(“Access”,2,3) will return 3 characters from 2 positions, that is, cce Len(“Access”) will return 6 Lcase(“ACCESS”) will return access Ucase(“access”) will return ACCESS Instr(“Operations”,”ra”) will return 4
Trim(“
Acc ess
“) will return “Acc ess”
Replace(“Account Transactions”,”Account”,”Daily”) returns Daily Transactions Strcomp(“Access”,”Access”) returns 0 Strcomp(“Access”,”Training”) returns “Training” is greater than “Access”
StrReverse(“access”) returns “ssecca”
Table 3.7: Text Functions 142
ADVANCED INFORMATION TECHNOLOGY TRAINING
-1
as
BUILDING CRITERIA EXPRESSIONS
3.4.2 Using Date and Time Functions These functions are used to handle Date and Time data. This group contains various functions such as extracting a part of date or adding two dates. Few of the important Date/Time functions, are shown in Table 3.8. FUNCTION NAME
EXPLANATION
EXAMPLE
Now()
Returns current date and time
Now() Returns 07/18/2012 12:20:55
Date()
Returns current date
Date()_ Returns 07/18/2012
Time()
Returns current time
Time()_ Returns 12:30:15
DateDiff()
Returns difference two dates. The DateDiff (“m”,#7/18/2011#,#12/3/2011#) interval for difference can be in terms Returns 5 as the difference between two of Days (“d”), months(“m”), Quarter dates in terms of months is 5. (“q”), years(“yyyy”), weeks (“ww”)
DateAdd()
Adds a specified interval to the given DateAdd(“q”,1,#1/11/2012#) will return Date. Intervals in this can be used as 4/11/2012 same in DateDiff As a Quarter added to January returns April. Extracts a portion of a date from the DatePart(“ww”,#2/3/2012#) returns 6 given date
DatePart() Month() MonthName() Year()
Returns month in integer from the Month(#12/1/2011#) returns 12 given date Returns name of the month, that is, MonthName(12) returns December given as an integer Returns year from a given date Year(#2/2/2012#) returns 2012 Table 3.8: Date and Time Functions
3.4.3 Using Math Functions Math functions are used for performing calculations on Numeric data. These functions provide us the property of performing various mathematical operations.
ADVANCED INFORMATION TECHNOLOGY TRAINING
143
DATABASE APPLICATION USING MS-ACCESS Some important mathematical functions are listed in Table 3.9. FUNCTION NAME Abs()
EXPLANATION
EXAMPLE
Returns the absolute value of a number
Fix()
Returns the nearest integer for a negative number
Abs (14) returns 14 Abs(-14) returns 14 Fix(-125.64) returns -125
Int()
Returns an integer for a specific value
Int(23.64) returns 23
Round()
Returns a number rounded to specified number of digits
Rnd()
Returns any generated random number
Round(18.234,2) returns 18.23 Round(18.246) return 18.25 Rnd() returns any Random no.
Sgn()
Sqr()
Returns an integer representing sign of a number 1 for –ve number 1 for +ve number 0 for Zero Returns square root of a number
Log()
Returns logarithm of a number
Sgn(-14) returns -1
Sqr(16) returns 4
Table 3.9: Math Function
3.4.4 Using Financial Functions Financial functions are used to perform many standard financial calculations, such as interest rates, annuity or loan payments, and depreciation. Some extensively used financial functions are listed in Table 3.10. FUNCTION NAME DDB()
FV()
144
EXPLAINATION
EXAMPLE
Returns the double-declining balance method of depreciation return based on the formula: Depreciation / period = ((cost salvage) * factor) / life
DDB(cost, salvage, life, period[, factor]) If we calculate depreciation for Rs.5, 000 computer with a Rs.200 salvage value and an estimated useful life of three years for the first year. DDB(5000,200,3,1)
Returns the future value of an annuity based on periodic, fixed payment and fixed interest rate
FV(Rate, Payment Periods, Payment [, Present Value] [, Type]) If we calculate Future value for a rate of 8% for 10 installments depositing an amount of Rs. 200 monthly. FV will be calculated as: FV(0.08/12,10,-200)
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS PV()
Returns the present value of an annuity PV (Rate, Payment Periods, Payment [, based on periodic, fixed payments to be Future Value] [, Type]) paid in future and fixed interest rate To calculate Present value of an annuity that will provide 5,000 a year for the next 20 years at a rate of .0825. We will use: PV(.08,5000,20)
SYD()
Returns the sum-of-years depreciation of an asset for a specific period
SYD(Cost Of Asset, Salvage Value, Length Of Useful Life, Period) To calculate the depreciation charges of a building that cost 365820 to build has a salvage value of 5390, and an estimated useful life of 30 years. We will use function SYD as: SYD(365820,5390,15,1)
PMT()
Returns the payment for an annuity based on periodic, fixed payment and fixed interest rate
RATE()
Returns the interest rate per period
To calculate a payment amount for a 6 percent loan of 360 months for 110000. The formula will be: PMT(.005, 360, -110000) Rate (nper, pmt, pv [, fv ] [, type ] ) To calculate interest rate on a Rs. 5,000 loan where monthly payments of Rs.250 are made for 2 years Rate(2*12,250,5000)
Table 3.10: Financial Functions Problem Scenario The Operations Manager of Apex Ltd. received many complaints from customers about the orders not reaching them on time. He wants a report to be submitted for all the orders which were delayed (under normal cycle orders must be shipped within 7 days). Solution The required query will use the tables Sales Order, the criteria will be placed on shipped date using the DateDiff () function. Steps for creating a query 1.
Click Create ribbon -> Queries -> Query Design to open the Query Design window. Select the Sales Order table from the Show Table window and click Add.
2.
Select the columns Sales Order Number, Sold to Customer, Sales Date, Ship Date, Shipped Via. The Query window appears, as shown in Fig. 3.4.1. ADVANCED INFORMATION TECHNOLOGY TRAINING
145
DATABASE APPLICATION USING MS-ACCESS
Fig. 3.4.1. Select required column Specify the criteria for Shipped Date as DateDiff("d",[Sales Date],[Ship Date])>7. The DateDiff() function returns difference between two dates, “d” forces it to return it in terms of days. The query looks like, as shown in Fig. 3.4.2.
Fig. 3.4.2. Specify Query criteria using Functions 146
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS 3.
Click
4.
Click
on the toolbar to save the query. Type the name of query as Orders Delayed. in Design ribbon -> Results to view the results, as shown in Fig. 3.4.3.
Fig. 3.4.3. Query Results
3.5 Working with Expression Builder The Expression Builder tool in Access helps build complex expressions. It contains easy access to access names and properties of columns of the tables. Expression Builder also contains a set of predefined functions in Access and also some prebuilt expression as to display page numbers. The Expression Builder window is shown in Fig. 3.5.1.
Fig. 3.5.1: Expression Builder Window ADVANCED INFORMATION TECHNOLOGY TRAINING
147
DATABASE APPLICATION USING MS-ACCESS
3.5.1 View of Expression Builder Expression box - A text box in which expressions are written. Any value from the Operators button or Expression Elements can be pasted into Expression Box. Operator buttons - Various operators are available in the Operators Buttons tab. We can just click any operator to get it in the Expression Box text box. Expression elements – Expression element contains three tabs
First one is for the objects in the database like Tables, Queries, Forms, or Reports.
Second is for the sub elements of the objects selected in the First tab like fields of the table, containers in Reports and Forms.
Third is for the properties of the element selected in second tab.
3.5.2 Complete view of all the three tabs in Expression Elements The first tab contains functions, the second contains different types of functions, and the third contains all the functions in a particular type. Click the Paste button to get any function in Expression Box, as shown in Fig. 3.5.2.
Fig. 3.5.2. Three tabs in Expression Elements 148
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS Problem Scenario Consider the case scenario discussed in section 3.3.4 database Apex Inventory Shipment. The Marketing Manager of Apex Ltd., found that there were few orders which were prepared on time, but could not be sent because of customer details are not available. By mistake, a sales executive while typing has put a wrong customer number. Customer Number general format is XXX-0000, where X represents character and 0 represents any digit. The executive has inserted five digits instead of four. List the names of all such customers. Solution For this query, again the Sales Order table needs to be used. The criteria would be formed using the text function Len (), length of Customer Number is normally 8 but would be 9 in this case. Expression Builder can be used to specify the criteria. Steps for second creating query 1.
Click Create ribbon -> Queries -> Query Design to open the Query Design window.
2.
Select the Sales Order table from the Show Table window and click Add.
3.
Select the Sales Order Number Sold to Customer, Sales Date, Ship Date, Shipped Via columns.
4.
Right-click on the Criteria tab of the Sold to Customer column and select Build from the drop-down, as shown in Fig. 3.5.3. The build will open the Expression Builder window.
Fig. 3.5.3. Select build from drop down 5.
The Expression Builder window appears, as shown in Fig. 3.5.4. ADVANCED INFORMATION TECHNOLOGY TRAINING
149
DATABASE APPLICATION USING MS-ACCESS
Fig. 3.5.4. Expression Builder window 6.
The expression in the criteria should be Len ([Sold to Customer]) > 8. To include the length () function, select Functions -> Built-In functions from first tab, Text on the second tab, and Len on the third tab from Expression Elements in Expression Builder, as displayed in Fig. 3.5.5.
Fig. 3.5.5. Select Len function 150
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS 7.
Double Click the Len function to include expression in Expression Box, as shown as in Fig. 3.5.6.
Fig. 3.5.6. Paste the expression 8.
Now the string which is a part of the Len () function must be replaced by field name. To do this select Table -> Sales Order from the first tab, Sale to Customer from the second tab in Expression Elements part of Expression Builder.
9.
Select the string argument of the Len () function and Double click to Paste the argument in Len() function. The column Name (Sale to Customer) will be pasted in place of string, the Expression Builder looks like as in Fig. 3.5.7.
ADVANCED INFORMATION TECHNOLOGY TRAINING
151
DATABASE APPLICATION USING MS-ACCESS
Fig. 3.5.7. Place the required column as function argument 10. Now click on > (Greater Than sign) from the Operators tab so that it gets pasted on Expression Box and write 3 after that so the Expression Builder window looks like as in Fig. 3.5.8.
Fig. 3.5.8. The Complete expression 152
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS 11. Click OK to save the expression. Note the written expression appears in criteria of the Sale to Customer field, as shown in Fig. 3.5.9.
Fig. 3.5.9. Expression appears in Criteria Click 12. Click
on the toolbar to save the query. Type the name of query as “Sale to customer Criteria”. in Design ribbon -> Results to view the results, as shown in Fig. 3.5.10.
Fig. 3.5.10. Query Results The Expression Builder makes it easier to remember function names and also avoids typing error in the name of the columns. The operators’ option can be used to place all the available operators in criteria expression.
3.6 Summary This chapter focused on creation of criteria expressions in Access 2010. The different components of the expression are – operators, operands, and functions. Operands can be considered as values used for performing operations. Operands can be further distinguished as literals, identifiers, and functions. Further, this chapter introduced different types of operators as – comparison, arithmetic, logical, and miscellaneous. Functions are built in code to help us work better with expressions. There are different types of functions available in Access to work with different data types. Various functions available are - Text Function, Date and ADVANCED INFORMATION TECHNOLOGY TRAINING
153
DATABASE APPLICATION USING MS-ACCESS Time Functions, Math Functions, and Financial Functions. Expressions can be written directly or by using an interactive tool Expression Builder to create expression. Expression Builder has various tabs as Expression Box, Operator Buttons, and Expression Elements.
Lab Exercises For Apex Inventory Shipment database of Apex Ltd. Provide a solution to the following problem scenarios: 1. A sales executive while inserting records in the Sales Order table by mistake inserted the Sales Date with a previous year. For instance, instead of 1/2/2012, he typed 1/2/2011. Write an Update query to add 1 year to all the dates which were written in previous year. 2. The Finance manager came to know that there had been a problem in receiving payments that were paid through Cheque or Electronic Card. Create a record set displaying all the invoices that were paid through Cheque, Master Card, or Visa Card. 3. For year-end review, the Vice President of the Company needs a report displaying a list of all the customers, and value and count of the orders placed by them. (To solve the above query create a Group By query on Customer, Sales Order, and Sales Item Description. Calculate the value of orders as Sum of Quantity and Price). 4. Considering the query in question 3, a customer named James having Customer Number as END-0010 wishes to pay his entire amount in monthly installments. Company charges an interest rate of 5% for the part payments. Calculate the amount that James has to pay as a monthly installment. (Use the PMT function). 5. Display a list of all the orders which have not been shipped. (Check for orders with NULL Shipped Date). 6. A sales person was trying to fetch all the customers from India from city – New Delhi, but he found that the city has been typed in many different ways. For instance New Delhi was also written as Delhi, N Delhi, or Old Delhi. Find all the records from table Customers which have country as India and contain ‘Delhi’ in city name. 7. The Marketing Manager defined a standard format of creating Customer Code as XXX-0000 where XXX are first three letters of Customer’s Company and 0000 is a four digit numeric code for customer. This format was not followed by some executives. Find all the customers for whom first three letters of the Customer Number does not match first three letters of their Company Name. 8. It was noticed that in the table Sales Item Description some values for Ship Qty are inserted as negative. Write a query to retrieve data having all the values of Ship Qty converted to positive and also the Price removing the decimal values. (Use math functions for the purpose). 9. Display a list of all the inventory items which are to be reordered. (Check all the Inventory which have Reorder Point greater than Inventory in Stock + Inventory on Order). 10. Considering the above query, retrieve a list of all the inventories which have not been ordered from past one month. (Make use of DateDiff and Date function) 154
ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS Multiple Choice Questions 1. For the Apex Inventory Shipment database, a list of orders placed ten months ago or more from the Sales Order table needs to be created. What would be appropriate query criteria for the Sales Date field?
(a)
DateValue(DateAdd(“yyyy”,-3,[Sales Date]) > Today()
(b)
>= 3 Months
(c)
Between 3 And 5
(d)
DateAdd("m",3,[Sales Date])
2. Which record will be retrieved if the query criteria is < #1/1/11#?
(a)
All values less or more than 1,195
(b)
Value less than 95 characters
(c)
Records with date before 2011
(d)
All of above
3. The query criteria on Shipped Date for deleting all the records from the Sales Order table which were shipped before April 2011 or were never shipped would be ____________?
(a)
">=#4/1/2011# OR IS NULL
(b)
Month() = April
(c)
IS NULL
(d)
None of the above
4. For the criteria BETWEEN 1/1/2011 and 12/31/2011, which rows will be displayed as result?
(a)
Display records between the dates 1/2/2011 and 1/1/2012
(b)
Display records between the dates 1/1/2011 and 12/31/2011
(c)
Display records whose dates equaled 1/1/2011 or 12/31/2011
(d)
All of the above
5. In the criteria expression Total Amount Paid: [Tax] + [Freight] + [Other], which value is an Identifier.
(a)
Total Amount Paid
(b)
[Tax]
(c)
+
(d)
All of the above
6. A report is needed to be prepared, checking all the orders that are pending to be shipped within one week. The criteria expression in Shipped Date can be? ADVANCED INFORMATION TECHNOLOGY TRAINING
155
DATABASE APPLICATION USING MS-ACCESS
(a)
> Today()
(b)
< DateAdd(“d”,7,”[Shipped Date])
(c)
> Date() + 7
(d)
= Now()
7. The tab in Expression Builder in which we write expressions is known as _____________.
(a)
Expression Elements
(b)
Operator Button
(c)
Expression Box
(d)
Expression Builder window
8. The criterion for the Category column in the Inventory table is IN (“Truck”, “Boat”, “Car”). This is equivalent to:
(a)
[Category] Like “Truck”,”Boat”,”Car”
(b)
[Category] = “Truck”,”Boat”,”Car”
(c)
[Category] = “Truck” AND [Category] = ”Boat” AND [Category] = ”Car”
(d)
[Category] = “Truck” OR [Category] = ”Boat” OR [Category] = ”Car”
9. Among +, <>, MOD, AND, <= operator which operator has the highest priority.
(a)
+
(b)
MOD
(c)
AND
(d)
<>
10. The criteria expression LIKE?a*.
(a)
Will match all text starting from A
(b)
Will match all text ending from A
(c)
Will match all text having second character as A
(d)
Will match all text starting with a digit
11. Which criteria would be used to find the records where the mode of payment is not known from Payments table?
156
(a)
[How Paid] IS NULL
(b)
[How Paid] = “”
(c)
NOT IN [How Paid] ADVANCED INFORMATION TECHNOLOGY TRAINING
BUILDING CRITERIA EXPRESSIONS
(d)
None of the above
12. The criteria [Sales Date] > #1/1/2011# XOR [Payment Terms] = “Cheque” will return records only when …
(a)
[Sales Date] is greater than 1-Jan-2011 And [Payment Terms] is “Cheque”
(b)
Either [Sales Date] is greater than 1-Jan-2011 Or [Payment Terms] is “Cheque”, but not both
(c)
[Sales Date] is greater than 1-Jan-2011 Or [Payment Terms] is “Cheque”
(d)
All of the above
13. Consider the query on the Inventory table:
This query will return:
(a)
All records from Inventory table
(b)
All records from Inventory table having Quantity in Stock greater than 20 AND Quantity on Order > 25.
(c)
All records from Inventory table except having Quantity in Stock less than 20 and Quantity on Order > 25.
(d)
All records from Inventory table having Quantity in Stock greater than 20 OR Quantity on Order > 25.
14. The Mid(“Apex Limited”,5,4) function will return
(a)
Apex
(b)
Ted
(c)
Limi
(d)
Apex Limited ADVANCED INFORMATION TECHNOLOGY TRAINING
157
DATABASE APPLICATION USING MS-ACCESS 15. The SGN() function is a ____________ type function:
(a)
Math
(b)
Financial
(c)
Text
(d)
Date & Time
16. The expression to combine first three characters of Customer First Name and last four characters of Sales Order Number placed by customer will be:
(a)
[First Name] + [Sales Order Number]
(b)
[First Name] & [Sales Order Number]
(c)
Left([First Name],3) + Right([Sales Order Number],4)
(d)
Left([First Name]) + Right([Sales Order Number])
17. The expression 3\4 will return
(a)
0.75
(b)
¾
(c)
0
(d)
None of the above
18. The Instr(4, “XXpXXpXXPXXP" , “P”) function will return
(a)
3
(b)
6
(c)
9
(d)
None
19. Which of the following is not a Date Time function?
(a)
Today()
(b)
Date()
(c)
Now()
(d)
MonthName()
20. A query with compound criteria, where both the criteria are written on the same row of two different fields. This will be creating_____________ compound criteria?
158
(a)
OR compound criteria
(b)
AND compound criteria
(c)
XOR compound criteria
(d)
EQV compound criteria ADVANCED INFORMATION TECHNOLOGY TRAINING
CHAPTER
4
MACROS AND SWITCHBOARDS
LEARNING OBJECTIVES Simplifying Task with Macros Creating a Macro Attaching a Macro Restricting Records Using a Condition Validating Data Using a Macro Automating Data Entry Using a Macro Managing AddingSwitchboards Unbound Controls Creating a Database Switchboard Modifying a Database Switchboard Setting the Startup Options
4.1 Introduction A macro allows you to automate tasks and add functionality to your forms, reports, and controls. Access macros let you perform defined actions and add functionality to your forms and reports. Macros in Access can be thought of a graphical and a simpler way to do programming. Every macro has a list of actions and arguments defined for each action. Macros can be used independently or attached to a form, report, or control events. Arguments provided in a macro can restrict, validate, or automate data entry. Microsoft Access 2010 has added new features to macros to eliminate the need to writing VBA code. Switchboards are forms available in Access 2010 to present data in the form so that users can focus on using the database as intended. A switchboard form presents the user with a limited number of choices for working with the application and makes the application easier to use. For example, a switchboard may give choice to open the tables, forms, and open or print reports.
4.2 Simplifying Task with Macros In Access, macros can be considered as a simplified version of VBA programming. Macros are used to execute any task that can be initiated with the keyboard or the mouse. Macros are written by specifying a list of to perform and providing arguments for these actions. Access 2010 provides enables macros so that they can automate responses to many types of events (events can be change in the data, the opening or closing of a form or a report, or even a change of focus from one control to another) without forcing actually using a programming language.
DATABASE APPLICATION USING MS-ACCESS
4.2.1 Creating a Macro In Access, macros can be created using the Macro Design window. This window can be opened by clicking Create Other Macro, as shown in Fig. 4.1.
Fig. 4.1. Create New Macro The Macro Design window is displayed in Fig. 4.2(A).
Fig. 4.2.(A). Macro Designer Window In the new Macro Designer for Access 2010, the layout more closely resembles a text editor. Actions and conditional statements displayed in a familiar top-down format that is used by programmers. Arguments are displayed inline in a dialog box as shown in Figure.4.2(B)
160
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.2.(B): Macro Designer Window Adding a new action or conditional statement is simple. Either select it from the actions drop-down list, from a right-click menu, or select it from the Action Catalog pane as shown in Fig. 4.3 to the right side of the Macro Designer.
Fig. 4.3: Action Catalog ADVANCED INFORMATION TECHNOLOGY TRAINING
161
DATABASE APPLICATION USING MS-ACCESS Actions Catalog: Actions are the basic building blocks of macros. MS Access 2010 provides a Action Catalog pane that contained large list of actions to be chosen, enabling a wide range of commands that can be performed. Some of the commonly used actions are: open a report, find a record, display a message box, or apply a filter to a form or report. A list of some commonly used actions in macro is displayed in Table 4.1. ACTION
DESCRIPTION
ApplyFilter
Applies a filter or query to a table, form, or report.
CancelEvent
Cancels the event that caused the macro to run.
Close
Closes the specified window or the active window, if none is specified.
CopyObject
Copies the specified database object to a different Microsoft Access database or to the same database with a new name.
DeleteObject
Deletes the specified object or the object selected in the Database window, if no object is specified.
Echo
Hides or shows the results of a macro while it runs.
FindNext
Finds the next record that meets the criteria specified with the most recent FindRecord action or the Find dialog box. Use to move successively through records that meet the same criteria.
FindRecord
Finds the first or next record that meets the specified criteria. Records can be found in the active form or datasheet.
GoToControl
Selects the specified field on the active datasheet or form.
GoToPage
Selects the first control on the specified page of the active form.
GoToRecord
Makes the specified record the current record in a table, form, or query. Use to move to the first, last, next, or previous record.
Maximize
Maximizes the active window.
Minimize
Minimizes the active window.
MoveSize
Moves and/or changes the size of the active window.
MsgBox
Displays a message box containing a warning or informational message.
OpenForm
Opens a form in the Form view, Design view, Print Preview, or Datasheet view.
OpenModule
Opens the specified Visual Basic module in the Design view.
OpenQuery
Opens a query in the Datasheet view, Design view, or Print Preview.
OpenReport
Opens a report in the Design view or Print Preview or prints the report immediately.
OpenTable
Opens a table in the Datasheet view, Design view, or Print Preview.
OutputTo
Exports the specified database object to a Microsoft Excel file (.xls), rich-text file (.rtf), text file (.txt), or HTML file (.htm).
PrintOut
Prints the active database object. You can print datasheets, reports, forms, and modules.
Quit
Quits Microsoft Access.
162
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS Rename
Renames the specified object.
Requery
Forces a re-query of a specific control on the active database object.
Restore
Restores a maximized or minimized window to its previous size.
RunApp
Starts another program, such as Microsoft Excel or Word.
RunCode
Runs a Visual Basic Function procedure.
RunCommand
Runs a command from Microsoft Access's menus. For example, File
RunMacro
Runs a macro.
RunSQL
Runs the specified SQL statement for an action query.
Save
Saves the specified object or the active object, if none is specified.
SelectObject
Selects a specified database object. You can then run an action that applies to that object.
SendObject
Sends the specified database objects as an attachment in an e-mail.
SetValue
Sets the value for a control, field, or property on a form or report.
SetWarnings
Turns all system messages on or off. This has the same effect as clicking OK or Yes in each message box.
StopAllMacros
Stops all currently running macros.
StopMacro
Stops the currently running macro. Use to stop a macro when a certain condition is met.
TransferDatabase
Imports or exports data to or from the current database from or to another database.
TransferSpreadsheet
Imports data from a spreadsheet file into the current database or exports data from the current database into a spreadsheet file.
TransferText
Imports data from a text file into the current database or exports data from the current database into a text file.
Save.
Table 4.1: Macro Actions Problem Scenario Kanika Mathur, a sales executive in Apex Ltd. is required to send a detailed report of all the orders that have been placed today to the Sales Head every evening in a form of an Excel sheet, also the same sheet also has to be uploaded in a shared folder for delivery to check. She thought to automate the process of transferring records so as to save the efforts required. Solution As a solution to the above problem, create a macro that transfers the table Orders into Excel and stores it in a shared folder using the TransferSpreadSheet Action. Then, use Send Object Action to mail it to the Sales Head. Steps for creating the macro 1.
Open Macro Designer. Click Create Macro & Code Macro. ADVANCED INFORMATION TECHNOLOGY TRAINING
163
DATABASE APPLICATION USING MS-ACCESS 2. Click AddNew Action drop-down box Select ExportWithFormatting.Note that the ExportWithFormatting option will also be available in Action Catalog. The Macro Designer window appears, as shown in Fig. 4.4.
Fig. 4.4 (A): Select Export with Formatting Action 3.
When we select an action that needs more than one argument, it would appear, followed by a box for each argument as shown in Fig. 4.4 (B).
Fig. 4.4 (B): Box for each argument and type necessary values
164
Object Type
:
Table
Object Name
:
Orders
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS Output Format
:
Excel Workbook (*.xlsx)
Output File
:
C:\Desktop\Order.xlsx
NOTE: Output File Name should include the complete absolute path of the shared folder. Macro Designer appears, as shown in Fig. 4.3 (B). 4.
Select the next action in the Query Designer window as EmailDatabaseObject and specify Action Arguments, as shown below in Fig. 4.4:
5.
Fig. 4.4: Action SendObject Object Type
:
Table
Object Name
:
Orders
Output Format
:
Excel Workbook (*.xlsx)
To
:
[email protected]
Cc
:
Bcc
:
Subject
:
Message Text
:
Edit Message
:
No (Select Yes to edit message before sending>
Template File
:
NOTE: The EmailDatabaseObject action can only be used if the Outlook is configured and is open. The To, Cc, Bcc, Subject, Message Text options can be set according to the requirement. 6.
Click Quick Access . The window prompts for the name of the macro, write the name of macros as MailCurrentOrders and click OK. Close the Macro Design window.
7.
Double-click the Macro Name under the Macro option in the All Access Objects tab to execute it.
Fig. 4.5: EmailDatabaseObject Macro ADVANCED INFORMATION TECHNOLOGY TRAINING
165
DATABASE APPLICATION USING MS-ACCESS All Macros are saved automatically in default name. Macro Builder can use many actions in a single macro or create multiple macros in one macro designer by using macro names. Macro can also be assigned shortcut keys using the AutoKeys macro.
4.2.2 Attaching a Macro A macro can be attached to an event of a control, a form, or a report. Macros are used to provide an added functionality to Access Objects. Macros can automate responses to many types of events without using a programming language. Events are the property of a form or a control. Macros are always attached to one event or another to perform some action. To view the events for a control, open its Property window and move to the Events tab as shown in Fig. 4.6. For example, if a button on a form is required to print a report, a macro which opens a report in print preview from can be attached to click event of the button. Access permits to create macros embedded to the control or attach an existing macro to events.
Fig. 4.6: Events in Form Properties
166
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS Problem Scenario Consider the problem scenario discussed in section 4.2.1. Now the same functionality is required to be added to the Orders form. This means that the Orders form should have a button that enables the user to export and mail the table. Solution Consider the form frmOrders which is based on Orders table, as shown in Fig. 4.7.
Fig. 4.7: Orders Form ADVANCED INFORMATION TECHNOLOGY TRAINING
167
DATABASE APPLICATION USING MS-ACCESS Now, add a button on the form and attach a macro to the click event of the button. Macro is the same as created in section 4.2.1 and exports and mails the list. 1.
Open the Orders form in the Design view. To do this, right-click the form and select Design View from the list.
2.
To add a button to the form, select Design -> Controls button to be added and draw it on the form, as shown in Fig. 4.8. Cancel the Command Button wizard that appears.
Fig. 4.8: Draw the button on the form NOTE: The Command Button wizard may not appear if Use Control -> Controls in Design is not selected.
Fig. 4.9: Use Control Wizards option 168
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS 3.
Open the control properties by selecting the Command button and press F4. Alternatively, select Property Sheet from Design -> Tools, as shown in Fig. 4.10.
Fig. 4.10: Select Property Sheet 4.
The Property window appears as shown in Fig. 4.11.
Fig. 4.11: Property Sheet for Button 5.
In the Format tab of Property Sheet, set the value of the Caption property to Export And Mail as shown in Fig. 4.12.
ADVANCED INFORMATION TECHNOLOGY TRAINING
169
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.12. Set Caption Property 6.
In the Event tab of the Property Sheet, set the value of the On Click event. To do this, click the list and select MailCurrentOrders, as shown in Fig. 4.13.
to open
Command24
Fig. 4.13: Set the On Click event Property NOTE: A macro embedded to the control can also be created, by clicking on Builder from the Choose Builder window that appears, as shown in Fig. 4.14. 170
button and selecting Macro
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Command24
Fig. 4.14: Create an embedded Macro 7.
The form appears as shown in Fig. 4.15; the macro will be executed on clicking the Export And Mail button.
Fig. 4.15: Click Button to execute the Macro ADVANCED INFORMATION TECHNOLOGY TRAINING
171
DATABASE APPLICATION USING MS-ACCESS Multiple macros can be created in a single Macro Designer window by giving each macro a different name and can be attached to an event of form or control by specifying their name.
4.2.3 Restricting Records using a Condition A macro condition is an expression that enables a macro to perform certain tasks only if a specific situation exists. When a condition is used in a macro, the macro performs a defined set of tasks depending on whether the expression returns the True or False value. When the expression returns True, all the actions are performed. When the expression returns False, none of the actions are performed. Conditions can be entered in the Conditions column of the Macro Builder window. A single condition can control more than one action. 4.2.3.1 The Where Condition The Where condition filters and selects records in reports or forms and their underlying tables or queries. This condition is applicable as an argument for the macro actions OpenForm and OpenReport. The Where condition is an Action Argument for macro actions such as OpenForm or OpenReport. For example, the Where condition specified for an OpenForm action can be used to compare and display matching records from two related forms. Problem Scenario In the Database Apex Inventory Shipment, as an enhancement to the Orders form created in Section 4.2.2, the Manager wishes to see the details of the Customer who has placed the order. Solution As a solution to the above requirement, a command button will be added to the form. On the click event of the command, a macro will be created that displays the Customers form restricted to the Customer Number for the order. For the purpose of displaying the customer information the frmCustomers form is created based on the Customers table, as shown in Fig. 4.16.
Fig. 4.16: Form frmCustomers 172
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS Steps for adding a button to frmOrders 1.
Open the frmOrders form in Design view. To do this, right-click the frmOrders form under the All Access Objects tab and select Design View from the list. The form opens in Design View, as shown in Fig. 4.17.
Fig. 4.17: Open form frmOrders in Design View 2.
To add a button to the form, select the button from Design -> Controls and draw it on the form, as shown in Fig. 4.18. Cancel the Command Button wizard that appears.
ADVANCED INFORMATION TECHNOLOGY TRAINING
173
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.18: Draw Command Button on Form 3.
174
Open the control properties by selecting the Command button and pressing F4. Set the value of Caption property as View Customer Details, as shown in Fig. 4.19.
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.19: Set Caption Property Steps for embedding a macro to On Click event of the command button 4.
In the Event tab of Property Sheet, set the value of the On Click event. To do this, click Click property. The Choose Builder window appears, as shown in Fig. 4.20.
ADVANCED INFORMATION TECHNOLOGY TRAINING
next to the On
175
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.20: Open the Choose Builder window 5.
176
In the Choose Builder window, select Macro Builder from the list and click OK. The Macro Designer window appears, as shown in Fig. 4.21(A).
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.21(A): Macro Designer window 6.
In the Add New Actions Dropdown list, select the OpenForm Action from the list. Set the value of Action arguments as shown in Fig 4.21(B):
Fig 4.21(B): Fill the arguments of OpenForm Action ADVANCED INFORMATION TECHNOLOGY TRAINING
177
DATABASE APPLICATION USING MS-ACCESS
7.
Form Name
:
Customers
View
:
Form
Filter Name
:
Where Condition
:
[Customer Number]=[Forms]![Orders]![Sold to Customer]
Data Mode
:
Yes
Window Mode
:
Click Design -> Close -> Close, as shown in Fig. 4.22(A).
Fig. 4.22(A): Close the macro 8.
A message box appears prompts to save the macro created, as shown in Fig. 4.22(B). Click Yes to save the macro.
Fig. 4.22(B): Confirm to save the macro
178
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS 9.
The created macro gets embedded in the Property window and is shown in the On Click property. The Property Sheet appears, as shown in Fig. 4.23.
Fig. 4.23: Property Sheet 10. To check the macro, open the frmOrders form in Form View and click the View Customer Details button. This should display the frmCustomers form only with the record of current customer, as indicated in Fig. 4.24.
Fig. 4.24: Customer Records restricted by Orders form. ADVANCED INFORMATION TECHNOLOGY TRAINING
179
DATABASE APPLICATION USING MS-ACCESS
4.2.4. Validating Data using a Macro Microsoft Access provides a variety of ways to control how data is entered in a database. For example, the data that a user can enter into a field can be limited to a range of values or to the format in which it must be entered. The validations can be defined at the table level by specifying table properties or the validation can be done at the form level. To validate data entry in a form, the properties of the controls may be used or alternatively all these validations can be defined using macros. Macros provide a good flexibility to place complex validation. Macros are useful for validating records when:
Validation rule is to be applied on multiple fields in the form or to same field in different forms.
To display customized error messages for different types of errors in the field.
Instead of Validation Rule, it must be just a warning message.
The validation involves references to controls on other forms or contains a function.
Table 4.2 lists some control events on which macro can be attached for Data Validation. Event Property
When the Macro Will Execute
Before Update
Before the entered data is updated.
After Update
After the entered data is updated.
Before Insert
After you type in a new record.
On Delete
In response to a deletion request, but before the record is deleted. Table 4.2: Event Property
Table 4.3 lists some macro actions that can be used as a response to validation. Action
Use Action To
Cancel Event
Prevents a user from posting a new record unless certain conditions are met.
GoToControl
Specifies where on the form the insertion point is to be placed.
MsgBox
Displays a custom message box. Table 4.3: Macro Actions for Data Validation
180
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS Problem Scenario Consider the frmOrders form created in Section 4.2.2. Rahul Sharma, the database developer in Apex Ltd. is asked to place a check on the Item Number field. It is to be ensured that Item Number should not be left blank. Solution To solve the above problem, a macro will be embedded on the Click event property of the Save Command Button. This macro will check if the Item Number is blank and will display a message accordingly. Steps for Validating Item Number 1.
Open the frmOrders form in Design View. To do this right-click the frmOrders form under the All Access Objects tab and select Design View from the list.
2.
Add a button to the form by selecting the button from Design -> Controls and draw it on the form. Cancel the Command Button wizard that appears.
3.
Open the control properties by selecting the Command button and pressing F4. Set the value of the Caption property as Save, as shown in Fig. 4.25.
Fig. 4.25: Set the caption property as Save. 4.
In the Event tab of Property Sheet, set the value of the On Click event. To do this, click side of the On Click property and open the Choose Builder window.
5.
Select Macro Builder from the list in the Choose Builder window, as shown in Fig. 4.26. Click the OK button.
ADVANCED INFORMATION TECHNOLOGY TRAINING
to the right
181
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.26: Open Macro Builder 6.
In the Macro Designer window that appears, add the conditions from selecting If from Add New Action Menu as displayed in Fig. 4.27.
Fig. 4.27: Add Condition 7.
In the Condition Argument textbox of the Macro Designer type the text [Item Number] IS NULL, this condition checks whether the Item Number value is blank.
8.
In the Add New Action Dropdown, select the CancelEvent action from the list. The Query Designer window appears, as shown in Fig. 4.28.
182
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.28: Specify Condition & Action 9.
In the next row, type … in the Condition tab. In the Action tab, select MsgBox from the list and specify Action Arguments as: Message
: Item Number cannot be left Blank
Beep
: Yes
Type
: Warning?
Title
: Validate
10. In the next row, type … in the Condition tab. In the Action tab, select GoToControl from the list and specify Action Arguments: Control Name
: Item Number
The Macro Designer window appears, as shown in Fig. 4.29.
Fig. 4.29: Specify GoToControl Action 11. Click Design -> Close -> Close, as shown in Fig. 4.30.
ADVANCED INFORMATION TECHNOLOGY TRAINING
183
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.30: Click Close to save and close the macro 12. A message box appears prompting to save the macro created, as displayed in Fig. 4.31. Click Yes to save the macro.
Fig. 4.31: Confirm to Save the macro Note that the created macro gets embedded in the Property window and is shown in the On Click property. Property Sheet appears, as shown in Fig. 4.32.
Fig. 4.32: Property Sheet 184
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS 13. To check the macro, open the frmOrders form in Form View and enter a new record with the values, as shown in Fig. 4.33.
Fig. 4.33: Enter a New Record 14. Click the Save button to save the record. Since the Item Number field is left blank the macro gets executed and the message is displayed, as shown in Fig. 4.34.
Fig. 4.34: Macro Executes ADVANCED INFORMATION TECHNOLOGY TRAINING
185
DATABASE APPLICATION USING MS-ACCESS Note that the multiple conditions and their post actions can be specified in the same macro; specifying the validation rule for other fields also.
4.2.5. Automating Data Entry Using a Macro Macros can be used to avoid errors and save time during data entry by automating the data entry process. Instead of having users type in the same data over and over for each record with the possibility of invalid data being entered, a macro can automate data entry. Microsoft Access Macros can be used to speed up the process of data entry. While automating the entry of data, it can be ensured that the possibility of errors in database data is minimized, which can have an impact on the accuracy of the data available for reports and queries. Macros can also be used for data entry where the value to be entered is dependent on value of other fields. For Example, a macro can be created to enter the total cost of an order if the unit price and quantity to be ordered of an item is provided. Table 4.4 lists the common events that can be used for Automating Data Entry. Event Property
When the Macro Will Be Executed
On Enter Before Update
Upon arriving on a control, but before the control has focus. Before the control data is updated.
After Update
After the changed control data is updated.
On Exit
Upon leaving a control, but before the focus is removed. Table 4.4: Event for Automating Data Entry
Table 4.4 specifies macro action used for Automating Data Entry. Action
Description
SetLocalVar
Enters a value automatically in a field. The field name and the value that needs to be entered in the field are mentioned as arguments. You need to enter the arguments in the Action Arguments pane for this action.
GoToControl
Specifies the field where the insertion point needs to be moved after a value.
Table 4.4: Macro Actions for Automating Data Entry Problem Scenario In the frmOrders form discussed in section 4.2.2, the Operational Manager wishes to see the total cost of the order, which would be computed as Quantity ordered * price of an Item.
186
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS Solution A text box as Total Order Cost is added to the form, and a macro is created on the Exit event of price to compute the total cost of an order. This macro first checks the value of Quantity is not null and then computes Total Cost. Steps for creating a macro to automate data entry 1.
Open the frmOrders form in the Design view. Add a TextBox to a form, select the TextBox control from Design -> Controls and draw it on the form, as shown in Fig. 4.35. Note that the TextBox also creates a label on the form so as the label to the Text value can be specified.
Fig. 4.35: Draw the TextBox on form ADVANCED INFORMATION TECHNOLOGY TRAINING
187
DATABASE APPLICATION USING MS-ACCESS 2.
Double-click the label and write the text Total Cost. Change the format of the label to match it with other controls. In this case, set the format as “Times New Roman, size 12, Bold”. The Form Design window appears, as shown in Fig. 4.35.
Fig. 4.36: Specify the text as Total Cost 3.
188
Open the control properties by selecting TextBox and pressing F4. In the All tab of Property Sheet, set the value of the Name property as “Total Cost”, as shown in Fig. 4.37.
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.37: Set the Name property 4.
In the Event tab of Property Sheet, set the value of the On Click event. To do this, click side of the On Click property and open the Choose Builder window.
to the right
5.
Select Macro Builder from the list in the Choose Builder window, as shown in Fig. 4.38. Click the OK button.
Fig. 4.38: Open Macro Builder 6.
In the Macro Designer window, add the Conditions tab by selecting Condition from Design -> Show/Hide. ADVANCED INFORMATION TECHNOLOGY TRAINING
189
DATABASE APPLICATION USING MS-ACCESS 7.
In the Condition tab of the Macro Designer type the text [Quantity] Is Not Null, this condition checks if the Quantity value is blank.
8.
In the Action drop down, select the SetLocalVar action from the list. Set the value of Action arguments as: Name
: Name of the local Vatriable
Expression : [Quantity] * [Price] The Query Designer window appears, as shown in Fig. 4.39.
Fig. 4.39: The Macro Designer window 9.
Click Design -> Close -> Close to save and close the macro. A message box appears prompting to save the macro created, as displayed in Fig. 4.40. Click Yes to save the macro.
Fig. 4.40: Click Yes to save the macro 10. The created macro gets embedded in the On Exit event property of the Price TextBox control. Property Sheet appears, as shown in Fig. 4.41.
190
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.41: Property Sheet 11. Open the frmOrders form in Form View and enter a new record with the values, as shown in Fig. 4.42.
Fig. 4.42: Insert a new record in frmOrders ADVANCED INFORMATION TECHNOLOGY TRAINING
191
DATABASE APPLICATION USING MS-ACCESS 12. As you enter the value for price and move to the next textbox, the On Exit event of the Price control gets executed and the total cost is calculated, as shown as Fig. 4.43.
Fig. 4.43: Automated Data Entry for Total Cost
4.3 Managing Switchboards A switchboard is a Microsoft Office Access 2010 form that facilitates navigation in Access and access to different parts of an application. It functions as an interface between the user and the application. A switchboard is similar to the Ribbon of the Access application. It provides users with direct access to the specific functions of the application and acts as an interface between the user and the application. Switchboard contains command buttons that execute specified actions. These buttons can be programmed to open forms, reports, queries. Each button on the switchboard triggers some action within the database or leads to another switchboard form. Switchboard forms are an invaluable way to keep users focused on using the database as intended. A switchboard form presents the user with a limited number of choices for working with the application and makes the application easier and user specific to use. The user’s login information can determine which of a 192
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS number of switchboard forms to use. For instance, a manager with a higher level of privileges may be given a form with more options than a clerical worker would be given.
4.3.1. Creating a Database Switchboard The Switchboard Manager is a dialog box that allows creating a switchboard for an Access database. It lists the switchboards currently available in a database and provides an option to create new ones. In each switchboard, command buttons can be added, deleted, or edited. The command buttons can be configured for accessing forms, reports, macros, or functions in the database. Switchboard Manager only allows a maximum of eight command buttons on a switchboard. The operations that the command button on switchboard can perform are listed in Table 4.6. Command
Action performed
Go to Switchboard
Opens a secondary switchboard.
Open Form in Add Mode
Opens a form in a mode that only allows new records to be added.
Open form in Edit Mode
Opens a form in a mode that allows any record to be added or edited.
Open Report
Opens a report in Print Preview.
Design Application
Opens the Switchboard Manager.
Exit Application
Closes the current database.
Run Macro
Runs a macro.
Run Code
Runs a Visual Basic function. Table 4.6: Different Commands that Switchboard can perform
When a switchboard is created with Switchboard Manager, Access creates the Switchboard Items table that describes what the display text and action performed by the buttons on the Switchboard form. Problem Scenario Employees of Apex Ltd. need to keep updating the company database frequently for various reasons. However, employees are confused over the interface that appears when the application is started. The application developer wishes to resolve this confusion by providing a clear and concise environment in which users can reduce the amount of time spent figuring out how to obtain the information they are looking for. Solution To resolve the problem of navigation in the database, a Switchboard form that contains buttons to open the Customers and Inventory tables and the frmOrders form needs to be created. Since switchboard is not capable of opening the tables directly through the Command button, so we have created macros to open the Customers and Inventory tables named as MacroCust and MacroInvent respectively. The structure of macros is displayed in Fig. 4.44. ADVANCED INFORMATION TECHNOLOGY TRAINING
193
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.44: Macro to open Customers and Inventory table NOTE: Notice that both the MacroCust and MacroInvent macros are created in the same Macro Designer window using the Macro Name property. Steps for Adding Switchboard in Access 2010 The Switchboard Manager is still available in Access 2010, but it's not included in the Database Utilities Ribbon as in Access 2007 and 2003. You have to launch it as doing the following steps as shown in Fig.4.44: Step 1: First click the File tab and Options button, then we will get into Access Options window; Step 2: Click the Quick Access Toolbar at left bar; Step 3: In the Choose commands from drop down box, select the Commands Not in the Ribbon item; Step 4: Select the Switchboard Manager item in the command list box; Step 4: Click the Add button; Step 6: At last click the Ok button at the bottom.
194
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.45: Open Switchboard Manager in MS Access 2010 Steps for creating Switchboard in Access 2010: On the New tab, in the Ribbon, click Switchboard Manager, as shown in Fig. 4.46.
Fig. 4.46: Switchboard Manager NOTE: If the database does not contain any switchboard, a message box as indicated in Fig. 4.47 appears confirming to create a new Switchboard.
ADVANCED INFORMATION TECHNOLOGY TRAINING
195
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.47: Confirming New Switchboard 1.
The Switchboard Manager Dialog box appears. Click New to create a Switchboard. Switchboard Manager is displayed as in Fig. 4.47.
Fig. 4.48: Switchboard Manager Dialog box NOTE: Instead of creating a new Switchboard, the default created switchboard can also be used. 2.
196
In the Create New dialog box, in the Switchboard Page Name text box, enter User Switchboard and then click OK to create a sub-switchboard with that name, as shown in Fig. 4.49.
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.49: Create New Dialog Box 3.
In the Switchboard Manager dialog box, in the Switchboard Pages section, verify that User Switchboard is selected and click Edit, as displayed in Fig. 4.50.
Fig. 4.50: Edit the switchboard to add buttons 4.
In the Edit Switchboard Page dialog box, click New to add buttons to Switchboard. The Edit Switchboard Item dialog box appears, as shown in Fig. 4.51.
ADVANCED INFORMATION TECHNOLOGY TRAINING
197
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.51: Create a New Button 5.
In the Edit Switchboard Item dialog box, in the Text field, type Customers as name of the button.
6.
From the Command list, select Run Macro.
7.
From the Form list, select MacroOpenTable.MacroCust and click OK. The Edit Switchboard window appears, as shown in Fig. 4.52.
Fig. 4.52: Provide details of the button 8.
198
Click OK to close the Edit Switchboard window, the created button appears in Items on the Switchboard tab, as shown in Fig. 4.53.
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.53: Customers Button 9.
Repeat steps 4 - 8 to add another button to the form which opens the Inventory table. The final Edit Switchboard window appears, as shown in Fig. 4.54.
Fig. 4.54: Create Button Inventory Steps to add frmOrders form to the Switchboard 10. In the Edit Switchboard Page dialog box, click New to add buttons to Switchboard. The Edit Switchboard Item dialog box appears. ADVANCED INFORMATION TECHNOLOGY TRAINING
199
DATABASE APPLICATION USING MS-ACCESS 11. In the Edit Switchboard Item dialog box, in the Text field, type Orders as name of the button. From the Command list, select Open Form in Add Mode. 12. From the Form list, select frmOrders and click OK. The Edit Switchboard window appears, as shown in Fig. 4.55.
Fig. 4.55: Create Orders Button 13. The final Edit Switchboard window appears, as shown in Fig. 4.56. Click Close to close the Edit Switchboard window.
Fig. 4.56: Final Edit Switchboard window 200
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS 14. The Switchboard Manager window appears. Select User Switchboard and click the Make Default button. This option will set the User Switchboard as default switchboard. The Switchboard Manager window appears, as shown in Fig. 4.57.
Fig. 4.57: Make User Switchboard as Default Switchboard NOTE: Notice that Switchboard Manager has created a new table Switchboard Items and a new form Switchboard. 15. To test the switchboard created, double-click Switchboard under All Access Objects -> Forms to launch the User Switchboard window. The switchboard form appears, as shown in Fig. 4.58.
Fig. 4.58: User Switchboard ADVANCED INFORMATION TECHNOLOGY TRAINING
201
DATABASE APPLICATION USING MS-ACCESS
Modify a Database Switchboard A switchboard created using Switchboard Manager can display only the default settings for the elements on the switchboard. Switchboards can be made more handy and effective by modifying the properties of a switchboard. Access provides different features to customize a switchboard. A Database Switchboard can be modified in the Design view using the Property Sheet pane. The VB Editor can also be used for making switchboard modifications. Switchboard can be modified by changing its design, moving controls, adding text, modifying text properties, adding graphics, and changing the control properties. To add or delete buttons to Switchboard, the Edit option in Switchboard Manager is used. Problem Scenario The developer noticed that the switchboard created in section 4.3.1 is not giving a professional look. He wishes to add the company logo to the switchboard. In addition, he wants to add a new button to the switchboard which will help the user to create an excel copy of data and mail it to the manager. Solution To add a company logo to the switchboard, modify the switchboard in the Design view. To add a new button to the switchboard, use the Edit option in Switchboard Manager. Create a command button to execute the macro MailCurrentOrders created in section 4.2.1. Steps for adding a company logo to Switchboard 1.
Right-click the switchboard under All Access Objects -> Forms and select the Design view from the list to open the switchboard in the Design view. The switchboard appears, as shown in Fig. 4.59.
Fig. 4.59: Open Switchboard in Design View 202
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS 2.
Click Design -> Controls -> logo button and browse to the logo image, as shown in Fig. 4.60.
Fig. 4.60: Form Design Tools View
Fig. 4.61: Print the desired logo 3.
The logo appears in the Switchboard form, as displayed in Fig. 4.62.
ADVANCED INFORMATION TECHNOLOGY TRAINING
203
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.62: The Switchboard form with logo. Steps to customize the text in Label 1.
Select the Apex Inventory Shipment label and press F4 to open the Property window.
2.
Set the value of caption property as Inventory Shipment Data. The Caption property is visible under the Format tab. The Property window appears, as shown in Fig. 4.63.
Fig. 4.63: Change Caption of the label 3.
204
Save the Switchboard form and open it in the Form view to view the changes made. The Switchboard form appears, as shown in Fig. 4.64.
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.64: Switchboard Form Steps for adding a new button to the Switchboard Form 4.
On the New Tab or where the Switchboard Manager in your tab, New Tab, click Switchboard Manager.
5.
The Switchboard Manager Dialog box appears. Select User Switchboard and click Edit to edit the switchboard, as shown in Fig. 4.65.
Fig. 4.65: Edit the Switchboard User Switchboard ADVANCED INFORMATION TECHNOLOGY TRAINING
205
DATABASE APPLICATION USING MS-ACCESS 6.
Edit Switchboard Page appears. Click New to create a button, as shown in Fig. 4.65.
Fig. 4.66: Create a new button 7.
In the Edit Switchboard Item dialog box that appears as a result, in the Text field, enter Mail and Create Excel copy.
8.
From the Command list, select Run Macro.
9.
From the Form list, select MailCurrentOrders and click OK. The Edit Switchboard window appears, as shown in Fig. 4.67.
Fig. 4.67: Add a button to run macro MailCurrentOrders 10.
206
Click OK to close the Edit Switchboard window, the button appears in Items on the Switchboard tab, as shown in Fig. 4.68.
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS
Fig. 4.68: Button appears in Edit Switchboard window 11.
Close the Edit Switchboard window and the Switchboard Manager window.
12.
To test the switchboard created, double-click Switchboard under All Access Objects -> Forms to launch the User Switchboard window. The switchboard form appears, as shown in Fig. 4.69.
Fig. 4.69: Switchboard Form
4.3.2. Setting the Startup Options Since most database users do not require direct access to the entire application, the switchboard can be used as a means to direct the user only to the objects specific to their job role. To make a switchboard appear while opening the database so as to make the application more convenient set the startup option of the database. Displaying the switchboard at startup helps to implement a level of security by hiding the key elements of the interface from the user. This allows users to access the database objects relevant to their tasks. ADVANCED INFORMATION TECHNOLOGY TRAINING
207
DATABASE APPLICATION USING MS-ACCESS Problem Scenario The Country Head of Apex Ltd., desired that the database Apex Inventory Shipment should be more users friendly. This means that users should not waste time navigating through various objects. The application should guide the user provide only the required functionality. Solution The Switchboard form has already made the application user friendly, with a difference that user needs to open the application search switchboard among the forms and then execute it. This is time-consuming a long process and user may be confused with various options and forms available. To avoid this, set the switchboard form at the Startup option so that as and when the user opens the application the Switchboard form should appear and user may select the required task from it. Steps to set the switchboard form at startup 1.
Open the Apex Inventory Shipment database and click
2.
Select Access Options from the list, as shown in Fig. 4.70.
.
Fig. 4.70: Open Access Options
208
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS 3.
The Access Options window appears select Current Database from the left tab, as shown in Fig. 4.71.
Fig. 4.71: Select Current Database 4.
Go to Application Options, click as shown in Fig. 4.72.
in the Display form and select Switchboard from the list that appears,
ADVANCED INFORMATION TECHNOLOGY TRAINING
209
DATABASE APPLICATION USING MS-ACCESS
Fig. 4.72. Select Switchboard for Display Form option 5.
Click OK to close the window.
6.
To test the startup option, close and reopen the database. The Switchboard form should display automatically.
NOTE: Other than switchboard, any other form can also be set as a database startup option. So it helps to create a login form or a switchboard form and launch it at the startup of database.
Summary Macros can be created from simple to complex with one or multiple actions. Macro can be executed as a separate object or can be attached to an event property of form, controls, or reports. The attached macros are executed when the event occurs. Macro can also be useful in restricting the number of records to retrieve using the Where clause available with certain actions. Using macro names, can help one macro object hold many macros. Conditions can also be specified with macros to validate the data entry. Macros can also be embedded with the control so that it is stored in the control and moves around with the control. Switchboards can help to navigate between the various database objects easily and manage data more effectively. The switchboard is essentially a steering wheel for users to find their way through the functions and forms that are available in the application. The switchboard is used as a navigation form, using buttons to 210
ADVANCED INFORMATION TECHNOLOGY TRAINING
MACROS AND SWITCHBOARDS display other forms. Switchboards are created using Switchboard Manager. A Switchboard Manager creates a switchboard form and a switchboard items table automatically. Switchboards can be set as database startup options so they should be displayed as the database is opened and can guide the user through proper options.
Lab Exercises Consider the Apex Inventory Shipment database of Apex Ltd. Provide a solution to below problems.
1. The executive from California has sent the details of all the Orders received today as an Excel 2007 (.xlsx) file named Orders_CA. Create a macro to convert the file to Access table and append the records to the Orders table. (NOTE: To append the records, create a query and execute it through macros.)
2. The executive in the Operations department are using the frmOrders form to view the orders placed. They want a functionality that the orders should be displayed only for the given period and the date should be accepted each time when they open the form. Create a macro to fulfill the requirement. (Use the Where clause)
3. The operations manager is facing a problem in checking whether the Items ordered are available or not. He wishes to have a button on frmOrders which should display the details of the Items requested in Order. Create a button on frmOrders and attach a macro to get desired functionality.
4. A form was created to track Inventory, as shown in the Fig. below. Attach a macro to the Calculate button that should make an auto entry to the field Order and Available. The order field should be set to Yes if sum of Quantity in Stock and Quantity on Order is less than Reorder Point. The Available Point should be set to Yes if the sum of Quantity in Stock and Quantity on Order is greater than Quantity ordered in Orders table.
Inventory Form ADVANCED INFORMATION TECHNOLOGY TRAINING
211
DATABASE APPLICATION USING MS-ACCESS
5. Consider the Inventory form created in previous example, create a macro to ensure that Category and Sub Category of an Item should not be left blank and Quantity on Order should not be less than Reorder Quantity. Display customized message if the validation is not followed.
6. The operations manager wishes to have the application customized for the users of Operations department. The operations manager asked the developer to create a switchboard form that should contain the link to open Inventory table, also it should display the Sales Orders along with their Invoices. Create a switchboard for the purpose.
7. Modify the above created switchboard so as when users selects inventory option another switchboard must be opened. This switchboard gives user option to display the entire Inventory, Inventory from a particular category and Items for which Quantity in Stock is more than 100.
8. Set the Switchboard created in Question No. 6 to the startup option of database so that it opens automatically as user opens the database.
9. Add a button to the Inventory form created in Question 4. The button should display all the orders from Sales Order Description table that were placed for the particular item. The item must be the item that is displayed currently in the form. (Attach a macro to the button for the purpose).
10. Edit the switchboard in Question No. 7. Add a button to the switchboard that should open the Inventory form.
212
ADVANCED INFORMATION TECHNOLOGY TRAINING
CHAPTER
5
DATA PAGES AND PROTECTION
LEARNING OBJECTIVES Hyperlink fields Working with Data Access pages Splitting a database Implementing security and encryption in database Setting passwords Converting an Access database to an ACCDE file a database with a digital signature Packaging Adding Unbound Controls
5.1 Introduction Access 2010 has come up with some major changes. The data access pages that were available in earlier version of access are not available in this version. However, if a database of previous version is opened in Access 2007, it displays data pages as read only. Access also has a data type hyperlink, which enable user to create a link for email, web page, and to the files on same or different machine. There are various protection mechanism provided by Access 2010 to make it secure and enhance its functionality. A large Access database used in a multiuser environment can be split into a front end and a back end file. To make the data more secure, Access database can be protected with a password. Access 2007 permits user to encrypt a database password so that it cannot be read by another utility. The access provides an ACCDE file format for the database that is to be distributed among various users. The ACCDE file is a locked version of original file and ensures that the user cannot modify the structure of objects. A new feature introduced in Access 2007 database is package and sign. A database can be packaged and digitally signed to make other users know that it is from a trusted source.
5.2 Hyperlink Fields Microsoft Access provides Hyperlinkdata type to create a clickable link to a Web page, file, or email address. A Hyperlink can be a UNC (universal naming convention: \\server\share\path\filename) path or a URL (Uniform Resource Locator: http://www.microsoft.com/.). It can store up to 2048 characters. The Hyperlink data type field holds combinations of text and numbers stored as text and used as a Hyperlinkaddress. It can have up to three parts:
The text that appears in a field.
The destination you go to when you click the cell (the URL or file path)
DATABASE APPLICATION USING ACCESS
Any sub-address within the file or page. Each part is separated by the hash symbol (#).For example, Microsoft Net Home Page http://www.msn.com.
The Hyperlink value can be inserted in two ways:
By typing the URL directly
Through the Insert Hyperlink window
The reference to a website or a webpage may be directly entered in the Hyperlink column, while a reference to a folder will be more easily done by the Insert Hyperlink window. Problem Scenario The Regional Delivery Head of Apex Ltd. found that it is difficult to trace the details of the Customer’s company just by its name. He wished to have a column in Customer’s table that should contain a link to the detailed document of the company stored as a word file on the same machine, so the entire information about the company can be easily viewed. The Regional Head requested database developer to help him with the requirement. Solution The database developer added a new field in the Customers table of Hyperlink data type. This field provides the functionality to user to give a direct link to the company’s webpage. Steps for adding a Hyperlink field in a table 1.
Right-click the Customers table under All Access Objects->Tables. Select the Design View, as shown in Fig.5.2.1.
Fig.5.2.1: Open Table Customers in Design View 214
ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION 2.
The Design window of table appears as displayed in Fig.5.2.2.
Fig.5.2.2: Customer Table – Design View 3.
Add a new column Company Details to the table and select the HyperlinkData Type, as shown in Fig.5.2.3.
Fig.5.2.3: Add Hyperlink Column ADVANCED INFORMATION TECHNOLOGY TRAINING
215
DATABASE APPLICATION USING ACCESS 4.
Save the changes made to the table and close it.
Steps to enter data in the Hyperlink field 5.
Double-click the Customers table to open it in the Datasheet view.
6.
Right-click theCompany Detailscolumn for the customer no. “BAN-0009” and select Hyperlink ->Edit Hyperlink, as shown in Fig.5.2.4. NOTE: Notice the other option available with Hyperlink. The Hyperlink can be opened in same or different windows, copied to other location, or deleted using these options.
Fig.5.2.4: Open Edit Hyperlink of column Company Details 7.
The Insert Hyperlink dialog box appears as described in Fig.5.2.5.
Fig.5.2.5: Insert Hyperlink dialog box 216
ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION 8.
Select the page to be attached as Hyperlink from the desired location. Specify the text to be displayed in the Company Details column and the URL for the file to be attached and click OK. The Insert Hyperlink dialog box is shown in Fig.5.2.6
Fig.5.2.6: Specify the URL for Hyperlink field Notice that the Hyperlink text appears in the column value, as shown in Fig.5.2.7.
Fig.5.2.7: Hyperlink appears in column Company Details 9.
The Hyperlink field can also be inserted using the Datasheet view. The field may contain link to an E-Mail, Web Page, or a document on same or different machine.
5.3 Working with Data Access Pages A Data Access Page is a special type of web page that allows users to interface with database using Internet Explorer. It is designed for viewing and working with data from the Internet or an intranet data that is stored in an Access database. Dataaccesspages make it possible to create data entry pages as HTML forms in Microsoft Access and publish them to a Website. Dataaccesspages are Web-related objects that combine the features of forms and reports. For each DataAccessPage created in Microsoft Access, Access generates the required HTML and ExtensibleMarkupLanguage (XML) code behind the scenes that represents the functionality of the data access page. These pages are saved outside the access database as a webpage. Beginning with Office Access 2007, the ability to create, modify, or import data access pages was no longer supported. However, data access pages in an Office Access 2007 database would still function. By using Access 2010, you can open a database that includes data access pages. However, the data access pages will ADVANCED INFORMATION TECHNOLOGY TRAINING
217
DATABASE APPLICATION USING ACCESS not function. When we open a data access page, we will receive an error message that states that Microsoft Office Access does not support this operation for Data Access Pages. An alternative to using data access pages is to create a Web database and publish to a SharePoint site by using Access Services.
5.4 Splitting a database Over a period of time, Microsoft Access databases may become more critical as more data and features are added to it, or it may be used in a multiuser environment. It gains a life of its own and the overall design becomes critical. One of the most important architectural designs to make databases meet the growing requirements is splitting the database. This is the way Access was designed to support multi-user databases and simplify the enhancement of the application over time. Splitting a shared database can help improve its performance and reduce the chance of database file corruption. When an Access database is split, it creates two files — a back-end database and a front-end database.A backend database holds all the tables, and a frontend database holds all the forms, queries, reports, macros, and the modules. In a multi-user configuration, the back-enddatabase is stored on a file server and a copy of the front-end is provided to every user that needs access to the database. The front-end links to the backenddatabase thus providing multi-user access to the main set of tables. When deployed, the forms are not sent from the database but open from the front-end locally and only the data actually entered moves to the back-end tables. This reduces the data traffic over the network. When to split an Access Database
To restrict the access of many users on the tables to avoid any changes to it
To reduce network traffic in a multiuser application
To maintain database because maintenance of data becomes easier as the data and application file are separate file
Problem Scenario The Database Administrator found that with the increase of number of users, the Apex Inventory Shipment database requires more security and also the efficiency to handle many users at the same time. The database needs to be managed in such a way that the authorizeduser must have access to the structure of tables; and also the multiple users can be handled. Solution The database administrator decided to create a split database as a precautionary measure to improve its working on a multiuser environment. Steps to create a Split Database 1. 218
Click Access Database from Database Tools ->Move Data -> Access Database button, as shown in Fig.5.4.1. The Database Splitter window appears. ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION
Fig.5.4.1: Click Access Database 2.
Click the Split Database button, as shown in Fig.5.4.2. Create the Back-end Database dialog box appears.
Figure 5.4.2: Database Splitter window 3.
Specify a name, a file type, and a location for the back-end database file, as shown in Fig.5.4.3.
ADVANCED INFORMATION TECHNOLOGY TRAINING
219
DATABASE APPLICATION USING ACCESS
Fig.5.4.3: Specify the Back End file 4.
Click the Split button, the split database is created and a confirmation prompt appears, as shown in Fig.5.4.4.
Fig.5.4.4: Database split confirmation NOTE: The front-end database is the original file, and the back-end database is located in the location that specified earlier in Database Splitter. The copy of database must always be created before splitting it, as the process cannot be undone.
5.5 Implementing security and Encryption in databases Security has always been an important part of database programs. In Microsoft Access 2010security features have been changed and enhanced. The Access 2010 allows database developers to quickly and easily lock down their creations without sacrificing the user-friendly features of the program. 220
ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION By default, Access 2010 disables all the potentially unsafe code or other components in a database, regardless of the version of Access that we used to create the database. Microsoft Access 2010 offers an improved security model that is simpler than earlier versions. The security feature of this version of Microsoft Access simplifies the process of applying security to a database. Microsoft Access incorporates several features to ensure the security to the data of Microsoft Access 2010. Microsoft Access 2010 integrates advanced ‘Encryption Technology’ which is much stronger than the previous versions of Microsoft. Third Party Encryption Technology can also be applied to the database of Microsoft Access 2010.
Access database in trusted location We can ensure security to Microsoft Access 2010 by placing the database in a trusted location. We can use the Trust Centre of Microsoft Access 2010 to find and create the trusted location for the database. In addition to creating the trusted database we can save, move or copy the database of Microsoft Access 2010 to the trusted location.
Encrypt Access Database In addition to database in trusted location, we can also provide security to the Microsoft Access 2010 database using the tools encoding and database passwords. We can provide password to encrypt the database so that the data is unreadable to all other tools of Microsoft Access 2010. The database can be accessed only by providing the correct password. New encryption technology integrated in Microsoft Access 2010 allows the user to encrypt the content of the database using password.
5.5.1 Implementing Security For maintaining data in a database, security is one of the major concerns of the database developer. MS Access 2010 has streamlined many of the security features which was there in previous versions of access. One of the basic improvements in Access 2010 security features is, Trust (enable) the disabled content in a database by clicking once to trust a database. Trust (enable) the disabled content in a database The Trust Center contains security and privacy settings for the Access 2010. Access 2010 disables all potentially unsafe code or other components; the warning message is displayed for it, as shown in Fig.5.5.1.
Fig.5.5.1: Security warning issued by Trust center The content disabled through the security features can be enabled. Click Enable Content on the warning messages to activate the disabled contents in the database. The setting for the Security option can be handled using File Tab ->Access Options, and selecting the Trust Center tab from the Access Option window, as shown in Fig.5.5.2.
ADVANCED INFORMATION TECHNOLOGY TRAINING
221
DATABASE APPLICATION USING ACCESS
Fig.5.5.2: Trust Center Click Trust Center Setting and manage the warning message through the Trust Center dialog box, as shown in Fig.5.5.3.
Fig.5.5.3: Trust Center window 222
ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION The Trust Center dialog box has an option which enables users to add trusted sites, trusted publisher, and manage macros and add-ins settings. Problem Scenario The Regional Head found that the users of Apex Inventory Shipment database were not able to interpret the security warning for Trust Center properly and could not decide if the content should be enabled. Regional Head asked database administrator to simplify the process for them. Solution The contents that are trusted and can be added to the trust center and enabled permanently. To specify that a given database is trustworthy and should be enabled by default, make sure that the database file is located in a trusted location. A trusted location is a folder or file path on your computer or a location on your intranet from which it is considered safe to run code. Default trusted locations include the Templates, Add-ins, and Startup folders. We can also specify our own trusted locations. Steps for adding the trusted content to the Trust Center 1. Click the File Tab,and then click Access Options. Click Trust Center, and then click Trust Center Settings. The Trust Center dialog box appears, as shown in Fig.5.5.4.
Fig.5.5.4: Trust Center dialog box 2. Select Trusted Locations. Then click Add new location, as shown in Fig.5.5.5.
ADVANCED INFORMATION TECHNOLOGY TRAINING
223
DATABASE APPLICATION USING ACCESS
Fig.5.5.5: Add trusted location 3. Microsoft Office Trusted Location window appears as shown in Fig.5.5.5. Click on the Browse button.
Fig.5.5.6: Browse the location 4. Select the appropriate path for the folder. Check the Subfolders of this location are also trusted option. Click the OK button, as displayed in Fig.5.5.7.
224
ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION
Fig.5.5.7: Add the trusted site and enable the subfolders NOTE: In a similar manner macros, add-ins, and other options can be managed using the Trust Center window.
5.5.2 Encryption in databases Encryptionhelps to protect the database from prying eyes. Security professionals recommend the use of encryption to protect sensitive information. Encryption scrambles and compact the database so that it is completely unreadable by a word processor or any other utility program. In earlier versions of Access, we could create user accounts and passwords using a feature named user-level security. Now, access 2010 reads and writes to the .ACCDB file format in chunks also known as pages. In the ACCDB, every encrypted 'page' has a unique key which is derived from a password hash (which includes random base data). Encrypting a database does not restrict access to database objects, but to open the database; the user must first enter a password. Decrypting the database reverses the process and restores it to its original form. Problem Scenario The database administrator wishes to secure the database in such a manner so that only the authorizeduser is able to access the database. Solution The database can be encrypted with a password to protect it from all users. To encrypt, the database must be opened in the Open Exclusive mode.
ADVANCED INFORMATION TECHNOLOGY TRAINING
225
DATABASE APPLICATION USING ACCESS Steps for encrypting a database 1. Open the Apex Inventory Shipment database in the Open Exclusive mode as shown in Fig 5.5.8.
Fig. 5.5.8: Database in open Exclusive mode 2. Select Encrypt with Password from File tab ->Info, as shown in Fig.5.5.9. The Set Database Password dialog box appears.
226
ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION
Fig.5.5.9: Encrypt with Password 3. Type a password in the Password box, and then type the same password in the Verify box, as shown in Fig.5.5.10; and click OK.
Fig.5.5.10: Set password window The database is now encrypted with a password. If any user tries to open the database, Access will prompt for password. The password set for the database can be decrypted by entering database password in password required dialog box as shown in Fig.5.5.10.
ADVANCED INFORMATION TECHNOLOGY TRAINING
227
DATABASE APPLICATION USING ACCESS
5.6 Converting an Access database to an ACCDE File Access provides some useful tools for managing databases. One of these tools converts databases to an ACCDE file from the current database. An ACCDE file contains compiled versions of all the code in the database with none of the source code. ACCDE databases run faster, but the user cannot access the source code for viewing or editing. ACCDE stands for execute only file. ACCDE file helps to create a secured database by protecting development investment by securing the design of the application’s objects and code. An .ACCDE file is a "locked-down" version of the original .ACCDB file. If the .ACCDB file contains any Visual Basic for Applications (VBA code), only the compiled code is included in the .ACCDE file. As a result, the VBA code cannot be viewed or modified by the user. Also, users working with .ACCDE files cannot make design changes to forms or reports. Benefits of an .ACCDE File
Reduces the size of the database
Optimizes memory usage and improves performance.
Protects the VBA code from being viewed or edited while still allowing it to run.
Allows users to update data and run reports without providing the entire database.
Problem Scenario The Country Head of Apex Ltd. asked the database developer to send a copy of the Apex Inventory Shipment database to another division of Company operating in India. The developer was advised to share a read-only copy as the other division users may try to change the structure of tables or forms, which might make the database not to function properly. Solution The Access original database can be converted to the .ACCDE file format to be protected from editing. The .ACCDE file format creates an execute-only file and is appropriate if database is to be distributed. Steps for creating an .ACCDE file 1. Open the Apex Shipment Inventory database. 2. On the File tab, click Save & Publish, and then under Save Database As, click Make ACCDE.as indicated in Fig.5.6.1.
228
ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION
Fig.5.6.1: Select Make ACCDE 3. Specify the location to store an ACCDE file and click Save, as shown in Fig.5.6.2.
Fig.5.6.2: Save the file as ACCDE ADVANCED INFORMATION TECHNOLOGY TRAINING
229
DATABASE APPLICATION USING ACCESS 4. Note that the copy of database as ACCDE is created in the specified location. Open the ACCDE file and confirm that the conversion was successful.
5.7Packaging a Database with a Digital Signature Access 2010 makes it easier and faster to sign and distribute a database. Package an Access database file, apply a digital signature to the package, and then distribute the signed package to other users. Packaging creates an Access Deployment file (.accdc) whose origin and integrity is certified by a digital signature. The Package-and-Sign feature places the database in an Access Deployment (.accdc) file, signs the package, and then places the code-signed package at a location. Packaging provides a digital signature to a file and let others know that database comes from a trusted zone. A digital signature confirms that the database has not been altered after the creation of package. Packaging encapsulates the database in an Access Deployment file (.accdc) and signs the package with a certificate. For external databases received, Access alerts about the presence of an untrusted certificate. The database can be package and digitally sign using Microsoft File ->Save &Publish -> Save Database as >Package and Sign, as shown in Fig.5.7.1.
Fig.5.7.1: Package and Sign a database
230
ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION
Summary The MS Access 2010 provides various security features to protect database. In addition, Access provides a way to connect to external sources by introducing a Hyperlink to an email, a web page, or some other file stored in same or different machine. The new version of Access supports few features from earlier version which are omitted. For example, Access 2010 does not support data access pages. However a user can view data Access pages if an earlier version file is opened in Access 2010. Users cannot edit Data Access Pages in Access 2010. If an Access database is used in a multiuser environment, splitting a database can help to reduce the network traffic. The split database creates a back end file – which can be stored on the server and the front end file which can be distributed to the users. The Access 2010 has improved security features. Though the Access 2010 has removed the user-level security, it has provided other features like storing the database password in an encrypted form. The encryption ensures that the database is not readable by other utility program. If an Access 2010 database is required to be distributed among different users, Access provides the .accde file which is an execute-only file that disables other users to view the code behind and modify the structure of objects. In addition, Access 2010 permits users to create a certificate by packaging a database and digitally signing it.
Lab Exercises The HR department of Apex Ltd. is maintaining the information of the employees in the Employees database. The Database contains following tables: TABLE NAME
DESCRIPTION
Employee Details
Storing the personnel details of Employees like Name and Contact info
Dependents
Stores information about employees dependents
Employee Salary
Stores salary structure for employees
Employee Job
Store Job details like department, Job Title, profile about the employees
Provide a solution to the following problem scenarios: 1.
The database Employees is required to be distributed within various divisions at different location. Split the database to a front end and back end file to be distributed among users.
2.
The HR database must be very secure so that only the authorized persons are able to open it and work with it. To provide an initial level security, encrypt the database with a password.
3.
A HR person wishes to store a link to the photographs of the employees stored in server in the Employee Details table. Create a link using hyper link feature toaccess the photograph of the employee.
4.
TheXYZ company demanded a copy of the database for the centralised location; the HR wishes that only the read-only copy of the database should be given. As a database administrator create an ACCDE file to make a read only copy of database.
ADVANCED INFORMATION TECHNOLOGY TRAINING
231
DATABASE APPLICATION USING ACCESS
Multiple Choice Questions 1.
The database developer wishes to create a field in the table Employee Salary, which should link to the web page displaying the salary slip of the employee. What would be an appropriate data type for the field? (a) Hyperlink (b) Text (c) Memo (d) Attachment
2.
The hyperlink field can store up to ______________ number of characters. (a) 1024 (b) 2KB (c) 1GB (d) 2048
3.
Which of the following object is not available in Access 2010? (a) Modules (b) Parameter Query (c) Data Access Pages (d) None of the above
4.
The database administrator created a split database and created a front-end database and back-end database file. Which of the file should be stored on the server? (a) Front-end database (b) Back-end database (c) Both of them (d) None of them
5.
If an Access 2007 database is converted to an Access 2010 format, which of the feature will be discarded? (a) Data Access Pages (b) Database Password (c) User Level Security (d) Both of them
232
ADVANCED INFORMATION TECHNOLOGY TRAINING
DATA PAGES AND PROTECTION 6.
The locking file used in Access 2003 database is known as ____________. (a) .mdb (b) .sec (c) .laccdb (d) .ldb
7.
The Sales people are facing problem deciding which of the external content should be enabled in database. The database administrator decided to add the required contents to trusted zone. Which window can be used for the purpose? (a) User Settings (b) Trust Center window (c) Content window (d) None of the above
8.
Access 2010 reads and writes to the .ACCDB file in chunks also known as _________. (a) Data (b) Window (c) Pages (d) File
9.
To create a read-only copy of the database, which of the following file format can be used? (a) .ACCDB (b) .ACCDE (c) .MDW (d) .ACCDT
10. Packaging and Sign feature available in Access 2010 creates a file with an extension __________. (a) .ACCDC (b) .ACCDE (c) .ACCDT (d) .ACCDB
ADVANCED INFORMATION TECHNOLOGY TRAINING
233
CHAPTER
6
IMPORT/EXPORTING DATA
LEARNING OBJECTIVES Integrating Access into business Importing XML Data into an Access Database Exporting Access Data to the XML Format Exporting Data to the Outlook Address Book Collecting Data through Email messages Importing CSV/TXT file into Access Database Importing anUnbound existing database into Access Database Adding Controls
6.1 Introduction Data may need to be exported or imported regularly. In this case, the data can be exported to a text file, spreadsheet, and other database formats. Access has the capability to use and exchange data among a wide range of applications. For example, data may be required to be extracted from other database files or obtain information from a SQL Server, Oracle, or a text file. Access can move data among several categories of applications:
Access database objects (all types, all versions)
Microsoft FoxPro
Text files (ANSI and ASCII; DOS or OS/2; delimited and fixed-length)
Microsoft Excel
ODBC databases (Microsoft SQL Server, Oracle Server, and other databases)
HTML tables, lists, documents
XML documents
Microsoft Outlook and Outlook Express
Microsoft Exchange documents
Microsoft SharePoint
Microsoft Word Merge documents
An import function copies externally stores data into an Access database, resulting in the imported data utilizing the format of an Access database. Information can be imported into new tables or existing tables, depending on
IMPORT/EXPORTING DATA the type of data being imported. An export function copies data from an Access table to some other software tool or data source, such as an XML document. The exported result uses the format of the other data source and not the format of an Access database. XML is a very important language for the web because of its wide use. Depending on various requirements, data can be imported or exported from MS Access to an XML document. Microsoft Access and Outlook have strong integration. Contact from Outlook can be imported to Access or E-mail messages can collect data from Access Database.
Case Study The database Apex Inventory Shipment will be used for importing or exporting of data.
6.2 Integrating Access into business As companies grow in size and complexity, the disparate applications and information need to remain productive become scattered across the corporate network. As a result, it is often required to access two or more systems to perform daily tasks. Access can interact with many applications through its import/export utility. Two major applications used widely to maintain and transfer data in a business environment are XML and Outlook.
6.2.1 Importing XML Data into an Access Database XML stands for eXtensibleMarkupLanguage. It is a similar language like HTML with a difference that in HTML every tag is defined by a specification whereas XML tags are completely variable. XML is a scripting language that can have features changed and added to it by any developer for any purpose. XML can be customized such that every XML document can have its own unique tags. The result is a browser-based language in which both the data and the language (the tags) are variable. The XML document must be based on following restrictions:
Every opening tag must have a corresponding closing tag.
Opening and closing tags must be properly sequenced and positioned in the hierarchy of an XML document.
An XML document must have a single root node and every other node in the XML document must be a descendant of the root node.
XML is case-sensitive.
Example of an XML document:
ADVANCED INFORMATION TECHNOLOGY TRAINING
235
DATABASE APPLICATION USING MS-ACCESS zacxcorp ZCXM 28.865 zaffymatinc ZFFX 92.250
XML elements are represented by tags. Elements usually consist of an openingtag and a closingtag. Openingtags consist of <, followed by the elementname, and ending with >. In this example, , , and are XML elements. XML attributes are contained within XML elements. Attributes are used within elements to provide more information about the element. These are represented as name/value pairs. Example of an attribute is Data. Every XMLdocument is based on a set of rules, known as XMLSchemaDefinition (XSD). XSD can be used to express a set of rules to which an XMLdocument must conform to be considered 'valid' according to that schema. In other words, an XMLschema describes the structure of an XML document. Moving information back and forth between computers is very easy, if an XML file is used. This type of processing can be used to transfer information between disparate platforms, databases, operating systems, applications, and companies. Microsoft Access 2010 recognizes XML files provided they have the structure expected by the software. Hence, importing XMLdocuments is easy with Access 2010. Problem Scenario At Apex Ltd, all the divisions across different states and countries send the details of the Orders received that day to the centralized unit in “New York” every day. This transferring process is a tedious job and is expensive in terms of size and portability. Solution To avoid the difficulty caused by transferring the data as an Access file, all data is transferred in the form of an XML document based on a standard XSD. These details are later inserted in a new table named as Orders_xxx where xxx represents the code of the division. The structure of the Orders table is shown in Fig.6.2.1.
236
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig.6.2.1: Orders Table Structure The standardized XSD structure is shown below in Fig.6.2.2.
Fig.6.2.2: XSD Structure The XML file sent from division “California” is displayed in Fig.6.2.3
ADVANCED INFORMATION TECHNOLOGY TRAINING
237
DATABASE APPLICATION USING MS-ACCESS 00011103 BEA-1664 ALS-00134 2008-01-11T00:00:00 Cash 2 6995 00031202 BAS-5400 BIL-00042 2008-03-12T00:00:00 PO Net 30 1 899
Fig.6.2.3: XML Document Steps for Importing XML Document 1.
Open the Apex Inventory Shipment database.
2.
Click on XML file in External Data ->Import& Link, as shown in Fig.6.2.4.
Fig.6.2.4: Import XML File 3.
238
The Get External Data window appears, browse to the XML file, and click OK as indicated in Fig.6.2.5.
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig.6.2.5: Browse the XML File 4.
Access scans the file and displays the structure of the table to be created in the import XML window, as shown in Fig.6.2.6.
ADVANCED INFORMATION TECHNOLOGY TRAINING
239
DATABASE APPLICATION USING MS-ACCESS
Fig.6.2.6: Import XML Window 5.
Select the appropriate option from the Import option available in the Import XML window. The available options are - Structure Only, Structure and Data, and Append Data to Existing Table(s). Select Structure and Data to copy data into a new table along with its structure. Click OK to confirm.
6.
The Final window appears. Select the option Save import steps so that the import process takes place without having to use the wizard again. Click Finish to close the wizard.
7.
The created table appears in the All Access Object tab. Double-click the table to view its data in the Datasheet view, as displayed in Fig.6.2.6.
Fig.6.2.6: Orders table created from XML File 240
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
6.2.2 Exporting Access Data to XML Format XML is a very simple and efficient way to exchange data between different computer programs. It is always simpler and easier to move data back and forth in form of XML files, rather than using the Microsoft Access 2010 files. Access permits to export both tables and queries to the XML format. In addition, the schema files specifying the structure of XML and the style sheet describing the presentation of data file can be imported. Problem Scenario Executives at Apex Ltd need to send a list of all the customers from “California”to the Sales Head in New York Office. Solution One of the ways to do this is by creating a query to fetch all Customers from “California”,export the query to the XML format, and send both the file and SchemaDefinition. Steps for creating a query 1.
Click Create ->Queries ->Query Design to open the Query Design window.
2.
Select the Customers table from the Show Table window and click Add, as displayed in Fig.6.2.8.
Fig.6.2.8: Show Table window 3.
Select the Salutation, First Name, Last Name, Company, Street, City, State, Zip/Postal Code, Phone,and Email columns from the Customers table and drag them to the Columns tab. The Query window appears, as shown in Fig.6.2.9. ADVANCED INFORMATION TECHNOLOGY TRAINING
241
DATABASE APPLICATION USING MS-ACCESS
Fig.6.2.9: Select Required Columns Now, we will add criteria to get only the records from “California”. 4.
In the Criteria tab of the State field write the literal “CA”, as indicated by Fig.6.2.10.
Fig.6.2.10: Specify criteria for State 242
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA 5.
Click
6.
Click
on the toolbar to save the query. Type the name of a query as “Customers from California”. in Design ->Results to view the results of the query, as shown in Fig.6.2.11.
Fig.6.2.11: Query Results Exporting data to XML 1.
Right-click the query Customers from California under All Access Objects ->Queries and select Export >XML File from the drop-down menu, as shown in Fig.6.2.12.
Fig.6.2.12: Right-click Query and click Export ADVANCED INFORMATION TECHNOLOGY TRAINING
243
DATABASE APPLICATION USING MS-ACCESS 2.
The Export - XML File window appears, as in Fig.6.2.13. Browse the path of the file or write its name in the File Name text box and click OK.
Fig.6.2.13: Export – XML File NOTE: The name of the file can be browsed or typed directly in the File Name textbox with its complete path. 3.
The next screen of the Export XML dialog box appears, and the following options are displayed: -Data (XML) - To export data to an XML document -Schema of the data (XSD) - To export the schema to an XML file -Presentation of your data (XSL) - To format data by using an Extensible Style Language file Select the required option, as shown in Fig.6.2.14 and click OK.
244
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig.6.2.14: Select information to be Exported NOTE: The Data (XML) check box mustbe selected for the Presentation of your data (XSL) drop-down box to be available. 4.
The Export – XML File window appears. Click Close to export to the XML document. NOTE: Check the file location specified, notice that the XML File and the Schema definition file is created.
6.2.3 Exporting Data to the Outlook Address Book Outlook is a personal information manager from Microsoft. Outlook is mainly used as an e-mail application but it also includes a Calendar, Task Manager, Contact Manager, note taking, a journal and web browsing. The OutlookAddressBook is a collection of address lists maintained in Outlook. AddressBook can be used to select names, e-mail addresses, and distribution lists. MicrosoftOutlook automatically matches every name typed from the AddressBook. The OutlookAddressBook is created automatically and contains the contacts in the Contacts folder. Similar to Access, Outlook is also widely used for managing personal and business contacts. Usually, it is required to communicate between Access and Outlook or vice versa. However, Access 2010 cannot directly export data to the Outlookfileformat, nor can Outlook 2010 directly import a table from an Access 2010 database. Problem Scenario Apex Ltd stores information in ApexInventoryShipment the database. The Marketing Manager wishes to send mail to all existing customers for some promotional offers. He also wishes to maintain a list for future references. Solution A quick way to do the above is to export all the contact to OutlookAddressBook so that they get stored permanently and be used for future reference. To export all contacts to Outlook, first export the data to a text file and then, to Outlookcontacts. Export Access data to a text file 1.
Right-click the Customers table under All Access Objects ->Tables. ADVANCED INFORMATION TECHNOLOGY TRAINING
245
DATABASE APPLICATION USING MS-ACCESS 2.
Select Export ->Text File, as shown in Fig.6.2.15.
Fig.6.2.15: Click on Export Text File 3.
The Export - Text File window appears, as displayed in Fig.6.2.16. Browse to the file or write its name in File Name box and click OK. NOTE: To export the data with Column Headers formatted, check the Export Data with formatting and layout option.
246
Fig.6.2.16: Provide File Name ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA 4.
Select Delimited–characters such as comma or tab separate each field and click Next. The Export Text wizard window is shown in Fig.6.2.17. NOTE: Choose the Fixed Width option, if the fixed space between all the columns is required.
Fig.6.2.17: Specify Delimited File 5.
Selecttab from choose the delimiter that separates your fields , and then select the Include Field Names on First Row check box to ensure that the field names are included in Text file as the Column headings, as shown in Fig.6.2.18. Click next to move to next page of the wizard. If you press ‘enter’ without selection, default setting will be taken..
ADVANCED INFORMATION TECHNOLOGY TRAINING
247
DATABASE APPLICATION USING MS-ACCESS
Fig.6.2.18: Specify Delimiter 6.
Enter the file name in the Export to File text box and click Finish.
7.
Click Close to close the final window. Check the specified location to confirm that the text file is created.
Steps for Exporting Text File to Outlook 1.
Select Import and Export in the File menu of Outlook Express, as shown in Fig.6.2.19.
Fig.6.2.19: Select Import and Export 248
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA 2.
Import and Export Wizard appears, as shown in Fig.6.2.20. Select Import from another program or file, and then click Next.
Fig.6.2.20: Import and Export Wizard 3.
Select Tab Separated Values (Windows) and click Next, as in Fig.6.2.21.
Fig.6.2.21: Import Tab Separated Values ADVANCED INFORMATION TECHNOLOGY TRAINING
249
DATABASE APPLICATION USING MS-ACCESS 4.
Browse to the Text File and click OK, as indicated in Fig.6.2.22. Click Next to move to next window.
Fig.6.2.22: Browse the required File NOTE: The Import a File window also provides options to manage the contacts in case the imported contacts create duplicates of contacts that already exist in Outlook. Under Options, choose the appropriate option from – Replace duplicates with Items imported, Allow duplicates to be created, or Do not import duplicate items. 5.
250
Select the Contacts folder and click Next, as indicated in Fig.6.2.23.
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig.6.2.23: Select Contacts Folder 6.
In the Map Custom Fields window appears as a result. Map each value from the text file to the fields in the Contact folder, as displayed in Fig.6.2.24. Click and drag every appropriate value from left and drop it to related field in right. Click OK.
Fig.6.2.24: Map related Fields ADVANCED INFORMATION TECHNOLOGY TRAINING
251
DATABASE APPLICATION USING MS-ACCESS NOTE: The Map Custom Field window contains some more option which is explained below:
To remove all mapping, click Clear Map.
To reset the original mapping, click Default Map.
To see additional records in the From list, click Previous or Next.
7.
Click Finish to complete the import.
8.
Select Contacts. All the contacts from Access table appear, as shown in Fig.6.2.25.
Fig.6.2.25: Contacts Imported
6.2.3 Collecting Data through Email messages Collecting Data through Email Message enables Access 2010 to gather data from people who are at different locations. To obtain this utility, Access 2010 works with Microsoft Office Outlook 2010 to generate and send an e-mail message. This feature sends a data entry form to the user in form of an e-mail message and later that data can be collected and saved in related table. 252
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA For example, consider a case where a sales man is taking orders in a different area and then needs to send details to a coordinator sitting in head office. This task consumes lot of time and also a single typing mistake may get wrong data. Using Collecting Data through Email Message, may reduce efforts at both ends as the data can be directly collected from the sales person through an E-mail and updated to table. To use this feature, Outlook2010 must be configured to receive e-mails and an Access table to store data must be created. Information in the email can be gathered in the form of HTML or InfoPath. The recipients need to allow HTML messages or have InfoPath installed (which is a part of the MS Office Professional suite). Problem Scenario At Apex Ltd everyday all the divisions across different states and countries send the details of the Orders received that day to the centralized unit in “New York”. Since transferring data as an Access table is expensive in terms of size and portability, all data is transferred in form of Excel file. These details are later inserted in the table. The Delivery head found that there are many transfer errors faced while importing and exporting data through Access and Excel which resulted in loss of some crucial information about Orders. Solution The above problem can be solved by collecting data through E-mail messages.The email using this features can be send toall sales people and they can reply to same mail with data filled up. For this purpose, the Orders table will be sent to each salesman using their e-mail address from the Sales Employee table. Steps for collecting data through E-mails 1.
Right-click the Orders table from the All Access Objects tab and select Collect and Update Data via Email, as shown in Fig.6.2.26.
Fig.6.2.26: Collect and Update Data via E-mail ADVANCED INFORMATION TECHNOLOGY TRAINING
253
DATABASE APPLICATION USING MS-ACCESS NOTE: Alternatively, click Create E-mail from External Data ->Collect Data. 2.
The Collect Data through e-mail messages window appears, as shown in Fig.6.2.27, Click Next.
Fig.6.2.27: Collect Data through e-mail messages 3.
In the next window that appears, select the format of data entry. Select HTML Form in this window and click Next, as shown in Fig.6.2.28 NOTE: Microsoft Office InfoPath Form can be selected if the recipient has both OfficeOutlook2006 and OfficeInfoPath2006or later installed to view and edit the InfoPathform.
254
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig.6.2.28: Select HTML form 4. In the next window, select whether to create an e-mail message to collect new information only, or to update existing information and Click next.
ADVANCED INFORMATION TECHNOLOGY TRAINING
255
DATABASE APPLICATION USING MS-ACCESS
Fig. 6.2.29: Select new or update existing information 5.
256
In the next window, specify the data to be included in the form. Click button to shift all the records from FieldsinTable to Fieldstobeincludedine-mailmessage as shown in Fig. 6.2.30. Alternatively, select only required field by clicking button.
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig.6.2.30: Select required field 5.
This resultant window is displayed in Fig. 6.2.31. Use the field properties of the current window to set the label of the field and mark them as read-only, as highlighted in the Figure.
ADVANCED INFORMATION TECHNOLOGY TRAINING
257
DATABASE APPLICATION USING MS-ACCESS
Fig.6.2.31: Resultant window 6.
Click Next to move to next window.
7.
Specify the way the replies should be processed. Replies can be managed automatically or manually. In automatic processing, replies are successfully exported to tables provided that Outlook is started. In manual processing, the replies reach the Outlookinbox but are required to be exported manually. Select the AutomaticProcesscheckboxrepliesandadddata to customers, as shown in Fig.6.2.32.
258
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig.6.2.32: Specify the automatic data processing 8.
Click Set properties to control the automatic processing of replies to display properties for automatic processing, as shown in Fig.6.2.33. Click Next.
ADVANCED INFORMATION TECHNOLOGY TRAINING
259
DATABASE APPLICATION USING MS-ACCESS
Fig.6.2.33: Properties for Automatic Processing 9.
260
In the next window, select the way to specify the e-mail addresses of the recipients – email address can be entered manually or can be chosen from a column in a table. Select the option Use the e-mail addresses stored in a field in the database, as shown in Fig.6.2.34 and click Next.
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig.6.2.34: Select email addresses from field in a database 10. In the next window, select the field from database that contains recipient email address. Select the An associated table select Employee option in the Select field. This determines who should receive the e-mail message. Similarly, select e-mail address in select field that contains email address, as shown in Fig.6.2.35. Click Next.
ADVANCED INFORMATION TECHNOLOGY TRAINING
261
DATABASE APPLICATION USING MS-ACCESS
Fig.6.2.35: Select field from associated table NOTE: Access automatically searches related tables to current table on the basis of relationship created. It then prompts to select the foreign key from current table and then map it to the table and finally select the mail address field from associated table. 11. The next window confirms the details for sending emails as – Subject, Introduction, To, CC, BCC. Leave the default or specify according to needs, as shown in Fig.6.2.36. Click Next.
262
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig.6.2.36: Set email options 12. Click Next. In the next window all email IDs are displayed. Select or deselect emails according to requirement. This window is displayed in Fig.6.2.37. Click Send.
ADVANCED INFORMATION TECHNOLOGY TRAINING
263
DATABASE APPLICATION USING MS-ACCESS
Fig.6.2.37: Select required emails NOTE: The collect data through email feature does not support AutoNumber, Attachment, OLE Object, or multivalve lookup fields. The mail status can be checked from Manage Replies in External Data ->Collect Data.
6.3. Importing TXT/CSV Data into an Access Database A text file contains unformatted readable characters, such as letters and numbers, and special characters such as tabs, line feeds and carriage returns. Access supports the following file name extensions — .txt, .csv, .asc, and .tab. To use a text file as a source file for importing or linking, the contents of the file must be organized in such a way that the importing and linking wizards can divide the contents into a set of records (rows) and each record into a collection of fields (columns). Text files that are organized properly fall into one of two types:
264
Delimited files: In a delimited file, each record appears on a separate line and the fields are separated by a single character, called the delimiter. The delimiter can be any character that does not appear in the ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA field values, such as a tab, semicolon, comma, space, and so on. Please see table 6.2.16 for example of comma as delimiter.
Fixed-width files :In a fixed-width file, each record appears on a separate line and the width of each field remains consistent across records. For example, the first field of every record is always seven characters long, the second field of every record is always 12 characters long, and so on. If the actual length of a field's value varies from record to record, the values that fall short of the required width must be padded with trailing space characters.
Problem Scenario AtNorthwind database Ltd, all the divisions across different states and countries send the details of the Orders details received that day to the centralized unit in “New York” every day. This transferring process is a tedious job and is expensive in terms of size and portability. Solution To avoid the difficulty caused by transferring the data as an Access file, all data is transferred in the form of an TXT/CSV document based on a standard XSD. These details are later inserted in a new table named as Orders_xxx where xxx represents the code of the division. The structure of the Orders Details table is shown in Fig.6.3.1
Fig. 6.3.1: Orders Details Table Structure
ADVANCED INFORMATION TECHNOLOGY TRAINING
265
DATABASE APPLICATION USING MS-ACCESS
Fig. 6.3.2: Orders Details Table in TXT format Steps for Importing TXT/CSV Document 8. Open the Northwind Database. 9. Click on TXT file in External Data ->Import & Link, as shown in Fig. 6.3.3.
Figure 6.3.3: Import TXT/CSV file 10. The Get External Data window appears, browse to the TXT file, and click OK as indicated in Fig. 6.3.4.
266
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig. 6.3.4: Browse the TXT/CSV File 11. Source of the data window appears; Select the appropriate option from the Import option available in the Import TXT window. The available options are – Import the source data into a new table in the current database, Append a copy of records to the table, Link to the data source by creating a linked table Data to Existing Table(s). Select Append a copy of records to the table as Order Details XXX and click OK as indicated in Fig. 6.3.5
Fig. 6.3.5: Select Append a copy of records to the table. ADVANCED INFORMATION TECHNOLOGY TRAINING
267
DATABASE APPLICATION USING MS-ACCESS 12. Access will automatically identify format of data. If we want to change the format of the data, we can do it by enabling Fixed Width radio button. Click Next to continue with the wizard as shown in Figure 6.3.6.
Fig. 6.3.6: Import Text Wizard 13. The Final window appears. Select the option Save import steps so that the import process takes place without having to use the wizard again. Click Finish to close the wizard. 14. The created table appears in the All Access Object tab. Double-click the table to view its data in the Datasheet view, as displayed in Fig. 6.3.7.
268
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig. 6.3.7: Orders Details table created from TXT File
6.4 Importing existing Database into an Access Database We can bring data from one Access database into another in many ways. Copying and pasting is the simplest method, but importing and linking offer we better control and flexibility over the data that we bring, and over how we bring that data into the destination database. Problem Scenario At Apex Ltd, the Human Resource Dept. wants to create a database of its employees across different city and states for its HRD related activities. Solution We need to copy a set of employee related table available in Northwind database. For example, we want to copy the Employees table and the Employees form to a second database that is HRD database, we need not to create a fresh structure of employee table. Importing enables us to copy an object and all of its related objects to another database in a single operation. Steps for importing existing database into an Access database 1. Create a Blank database name HRD database. 2. Click on Access file in External Data ->Import & Link, as shown in Fig. 6.4.1.
Fig 6.4.1: Import Access Table ADVANCED INFORMATION TECHNOLOGY TRAINING
269
DATABASE APPLICATION USING MS-ACCESS 3. The Get External Data window appears, browse to the Access file, and click OK as indicated in Fig. 6.4.2.
Fig 6.4.2: Browse Access Database 4. Selecting the Ok we got the Import Objects dialog box select the Employees table and click Ok.We can also import Forms, Report, Macros, and Modules etc. as per your requirement as shown in figure 6.4.3.
270
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA
Fig 6.4.3: Import Objects 5. The created table appears in the HRD Access Object tab. Double-click the table to view its data in the Datasheet view, as displayed in Fig. 6.4.4.
Fig 6.4.4: Employees Table in HRD Database.
ADVANCED INFORMATION TECHNOLOGY TRAINING
271
DATABASE APPLICATION USING MS-ACCESS
6.5 Summary This chapter discussed about importing and exporting data in Microsoft Access. Access is a significant application for maintaining data. Hence it’s very important that it should be able to communicate to and fro with other applications. XML is a language meant for universal communication and it is important for Access to be able to import and export data from XML. MS-Access can also create a schema definition and also style sheet formats for exported XML. Another common way of maintaining contacts and other information is using Microsoft Outlook. Access and Microsoft Outlook can integrate. The integration could happen not directly but through an intermediate Text file. Access Contacts can be exported to the Text file and then can be imported by Microsoft Outlook. Microsoft Access 2010 has a feature which enables to collect data through email messages. An email can be sent based on existing table or query and replies can be automatically managed to be updated in Access. This feature of MS Access saves a lot of time and efforts by direct communicating with Microsoft Outlook.
Lab Exercises For the Apex Inventory Shipment database of Apex Ltd. Provide a solution to below problems. 1.
A list of all the Orders that are to be dispatched today is required to be sent to the transport department. The problem is that the transport department doesn’t have MS-Access software installed. So it is required to convert the file into XML format and send it through mail.
2.
Considering the problem discussed in Question 1, the department needs to make sure that the data transferred is correct and has the required details. Also, they need to standardize a format for future transfer of data in XML format. Create a schema definition and style sheet file for the above XML document.
3.
A customer placed an order online. The details of the orders are stored in an XML file named CustNo_Orders. Create an Access table to store the details of this orders.
4.
The Company is working on strengthening its customer relationship. For this, Sales executive needs to take an appointment on email from each customer and meet them to take feedback on Company’s products and services. Get all the contacts for the New York sales executive into his Outlook contact so he can use them easily.
5.
The company has asked its existing customer to send the details of their relatives and friends who may be interested in Company’s products. For this, the company needs to mail a Customer profile form to each of its customer as that they can fill it and send it.
Multiple Choice Questions 1. For the Apex Inventory Shipment database, a list of all the salesperson needs to be sent to the Marketing Head. The list would be further updated in a centralized server. What would be the best format to send the list, considering the size in megabytes and varied nature of operating systems? (a) 272
As an Access Table ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORT/EXPORTING DATA (b)
As a data entry form
(c)
embedded with some other application
(d)
as a XML document
2. The file that defines the structure, in an XML document is called? (a)
XSD
(b)
DOM
(c)
XSLT
(d)
XML Structure File
3. The Marketing Regional Head requires sending a mail to all the sales executive to appreciate their working and redefine their targets of month. He has a list of all executives maintained in an Access table. Which feature in Access 2010 can be used for the purpose? (a)
Import and Export
(b)
Forms
(c)
Collect Data by through email message
(d)
Export data to Outlook Address Book
4. As a solution to the problem discussed in Question 3, the Marketing Regional Head needs to follow which of the below mentioned steps? (a)
Export the Access table to Text File and import the Text File from Outlook
(b)
Use Export to Outlook feature in Access
(c)
Export the Access table to Excel format and collect emails from the Excel file
(d)
Both a and b.
5. Once a mail is sent using the collect data through email message feature in Access 2010. The mail status can be checked using _______________. (a)
Export to Outlook
(b)
Options in Tool menu of Access
(c)
Manage replies
(d)
All of the above
6. XML is a language similar to HTML and consists of __________ (a)
Programming structure and loops
(b)
Tags, Elements and attributes ADVANCED INFORMATION TECHNOLOGY TRAINING
273
DATABASE APPLICATION USING MS-ACCESS (c)
Style sheets
(d)
All of the above
7. The ___________ type of data cannot be collected using Collect data through email messages. (a)
Text
(b)
Number
(c)
Date/Time
(d)
AutoNumber
8. To export an access table to an XML File, which of the below steps must be followed? (a)
Right-click the table and select Export ->XML
(b)
Go to External Data ->Export, click on More and select XML
(c)
Right-click the table and select send as XML
(d)
Both a and b
9. In which formats can the Collect Data through email message feature can send the data entry form? (a)
HTML and InfoPath
(b)
Access Forms
(c)
Visual Basic Application
(d)
Excel attachment
10. The Operational Head needs data of all the customers from his location from an executive who in Los Angeles. What would be the best way to transfer data?
274
(a)
Export data by applying filter on Access table
(b)
Create a query to fetch customers from Los Angeles and export it as an XML file
(c)
Export Access query
(d)
Attach Access query to a mail
ADVANCED INFORMATION TECHNOLOGY TRAINING
UNIT-2 ADVANCE MS-EXCEL
CHAPTER
1
WORKING WITH XML
LEARNING OBJECTIVES To gain understanding of XML To understand XML in Excel To understand Creating XML Maps from Excel file To understand Exporting & Importing XML data To understand working with XML tables To understand refreshing data from XML
1.1 Introduction Imagine CFO of a company who regularly looks at financial data. He wants to specify a range of dates and then get aggregate financial data relating to those periods. He wants to see Financial Figures, Revenue streams, Costs summarized by weeks within the specified range. He wants to see the raw data as well as charts showing these trends for the specified date range. To achieve this some staff, has to sift through lots of data and create separate spreadsheet reports for the different scenarios. The load on IT is huge in the sense that they have to cater to demands of not only CFO but whole lot of diverse departments like Sales, Procurement etc. A more viable alternative would be where we have an Excel spreadsheet that could adapt itself to deliver the various reports the CFO needs as well as one that other departments could reuse and adjust for their similar needs. The way out is XML, but let’s first understand what XML is.
1.2 Understanding XML XML is a technology that is designed for managing and sharing structured data in a human-readable text file. XML follows industry-standard guidelines and can be processed by a variety of databases and applications. Using XML, application designers can create their own customized tags, data structures, and schemas. In short, XML greatly eases the definition, transmission, validation, and interpretation of data between databases, applications, and organizations.
ADVANCE MS-EXCEL XML was designed to transport and store data.
XML stands for EXtensible Markup Language
XML is a markup language much like HTML
XML was designed to carry data, not to display data
XML tags are not predefined, we must define our own tags
XML is designed to be self-descriptive
XML is a W3C Recommendation
The simplest way to explain XML is as a structured way of storing information. The difference between an XML document and a database (which is also a way of storing structured information) is: 1. A database is a heavy system in that a lot of software goes into creating and maintaining a database; an XML document is based on tags, similar to a HTML document; the difference is that the tags can even be user defined, which means we can store data the way we want, as long as we create the software which can decipher what the data stands for. 2.
Even a browser can interpret common XML documents which rely on standard tags.
3. Every database system is proprietary in the sense that even though each can interface with another through defined protocols, the internals are all hidden; an XML document is defined by tags which are within the document, so it is totally open. XML stands for
EXtensible XML is extensible. It lets us define our own tags, the order in which they occur, and how they should be processed or displayed.
Markup The most recognizable feature of XML is its tags, or elements
Language XML is a language that’s very similar to HTML, but much more flexible. XML does not DO anything. XML was created to structure, store, and transport information.
The following example is a note to Sachin, from Mahendra, stored as XML: Sachin Mahendra Reminder Meet me at IPL!
278
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML The note above is self-descriptive. It has sender and receiver information, it also has a heading and a message body. Honestly, XML document does not DO anything. It is just information wrapped in tags. To send, receive or display it, software would be needed. XML allows the author to write their own Tags and their own data structure. XML documents form a tree structure that starts at "the root" and branches to "the leaves".
The first line is the XML declaration. It defines the XML version (1.0) and the encoding used (ISO8859-1 = Latin-1/West European character set).
The next line describes the root element of the document (like saying: "this document is a note"):
The next 4 lines describe 4 child elements of the root (to, from, heading, and body): Sachin Mahendra Reminder Meet me at IPL!
And finally the last line defines the end of the root element:
This XML document contains a note to Sachin from Mahendra
XML Documents Form a Tree Structure .....
The syntax rules of XML are very simple and logical
Every bit of data has to start and end with an identical tag: Data
Tag names are case sensitive. and are NOT valid tags because the capitalization in the end tag is not the same as the capitalization in the begin tag.
The XML file must begin and end with a root tag. There can only be one root tag in a file. In the example above, the root tag is .
We can have an empty tag - put the slash at the end of the tag instead of the beginning:
If we nest tags, we must close the inner tag before closing the outer tag. - data
will work, but - data
will not.
XML Attribute Values must be put within quotes.
Whether XML File is Valid or not can be checked at http://www.stg.brown.edu/service/xmlvalid/ ADVANCED INFORMATION TECHNOLOGY TRAINING
279
ADVANCE MS-EXCEL XML Element An XML element is everything from (including) the element's start tag to (including) the element's end tag. An element can contain:
other elements
text
attributes
or a mix of all of the above...
XML allows us to separate information from presentation An element consists of an opening tag, its attributes, any content, and a closing tag. A tag – either opening or closing – is used to mark the start or end of an element. A node is a part of the hierarchical structure that makes up an XML document. "Node" is a generic term that applies to any type of XML document object, including elements, attributes, comments, processing instructions, and plain text. XML Attributes Attributes often provide information that is not part of the data XML Schema To ensure that everyone plays by the rules, we need a Document Type Definition (DTD), which is called XML Schema, whose purpose is to define the structure of an XML document. It’s a lot like a rule book that states which tags are legal, and where.
1.3 XML in Excel Microsoft Office Excel makes it easy to import Extensible Markup Language (XML) data that is created from other databases and applications, to map XML elements from an XML schema to worksheet cells, and to export revised XML data for interaction with other databases and applications. Think of these XML features as turning Office Excel into an XML data file generator with a familiar user interface. Excel works primarily with two types of XML files:
XML data files (.xml), which contain the custom tags and structured data.
Schema files (.xsd), which contain schema tags that enforce rules, such as data type and validation.
The following are key scenarios that the XML features are designed to address:
Extend the functionality of existing Excel templates by mapping XML elements onto existing cells. This makes it easier to get XML data into and out of our templates without having to redesign them.
Use XML data as input to existing calculation models by mapping XML elements onto existing worksheets.
Import XML data files into a new workbook.
280
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML
Import XML data from a Web service into Excel worksheet.
Export data in mapped cells to XML data files independent from other data in the workbook.
1.4 XML Maps XML schemas in Excel are called XML maps. XML maps link the cells in a worksheet to the elements (items) in an XML schema. We must build our maps from XML schemas. Because schemas don't contain data, our mapped cells remain blank until we import or otherwise load data into them.
Inferred Schemas If there is no schema, Excel has a great facility where it infers one from the structure of the tags in an XML data file.
Xml Data File Format vs. XML Spreadsheet Format The XML Data format allows us to save our data to standard XML data files. The XML Spreadsheet format is proprietary, and requires Excel 2002 or later.
1.5 Create An XML Data File and XML Schema File From Worksheet Case Study 4.1: We have a salesman wise Invoice List in excel having the headers as which has Sales Id, Salesman, Invoice, Customer and Amount as shown in Fig. 1.5.1. We want to convert it into XML so that the data can be shared by other applications.
Fig. 1.5.1. Sales list Strategy: One simple approach we could think of is to use “Save As” option in Excel and to save the file as XML. Seems like a simple approach, But it doesn’t work, as we try, we get a message that there were no XML mappings found in the workbook. In order to export an Excel worksheet to XML we have to add XML Mappings to the file ADVANCED INFORMATION TECHNOLOGY TRAINING
281
ADVANCE MS-EXCEL
In order to create XML File from worksheet we have to use an add-in “OfficeExcel2003XMLToolsAddin. exe” which is downloadable from Microsoft’s site http://www.microsoft.com/enus/download/details.aspx?id=3108.
When downloaded.
Run that exe file which will install at c:\Office Samples\OfficeExcel2003XMLToolsAddin.
Then to install add-in, we go to File> Option>Add-ins>Excel add-in and browse to locate the file which will be at c:\Office Samples\OfficeExcel2003XMLToolsAddin select the file XmlTools.xla.
Thereafter, the add-in would be available for installation as shown in Fig. 1.5.2. select XMLTools
XML Tools would be available in add-Ins Ribbon
Fig. 1.5.2. Add-in Dialog Box
Select the XML tools in the Add-Ins Tab and 'Convert range to an XML list'.
Fig. 1.5.3. XML Tools
282
We get a Convert range to an XML List dialog box as shown in Fig. 1.5.4
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML
Fig. 1.5.4. Convert Range to XML
Select range of cells to convert.
Select first row contains column names.
Optionally we can choose 'Advanced' to enter our own name for the root of the document and for each row.
At this stage it asks whether to use existing formatting select that option
Fig. 1.5.5. Use Existing formatting
Click ok we see that our range has changed to Table
ADVANCED INFORMATION TECHNOLOGY TRAINING
283
ADVANCE MS-EXCEL
Fig. 1.5.6. XML Source
At this stage if we go to Developer>XML> Source we can see the XML map on right side panel.
We could then go to Export in XML Tab and export the file as XML
Alternatively, we can simply Save the spreadsheet as XML data with an xml extension.
Our file is converted to XML as shown in Fig.1.5.7.
Fig. 1.5.7. Excel converted to XML Gist: We have created XML from Sales List in Excel Commands Learnt: Developer > XML Food for thought: If, the spreadsheet contains dates or times, we may have problems in conversion, because excel converts it into numbers. Best approach here would be perhaps, reentering the dates as text field.
284
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML
1.6 Create an XSD Schema File To create a XSD Schema file,
Select the XML tools in the Add-Ins Tab.
Select “Create XSD files for the XML Schema at the active cell”
Fig. 1.6.1. Create XSD Files
An XSD Schema file is created as shown in Fig. 1.6.2.
Fig. 1.6.2: XSD File
1.7 Delete an XML Map If we want to delete the XML Map created above we go to XML> Source Pane> XML Maps and a dialog box will appear as shown in Fig. 1.7.1. We have to simply select the map we want to delete and Click “Delete”
Fig. 1.7.1. Delete XML Map ADVANCED INFORMATION TECHNOLOGY TRAINING
285
ADVANCE MS-EXCEL
1.8 Working with XML Tables By using XML maps, we can easily add, identify, and extract specific pieces of business data from Excel documents. For example, an invoice that contains the name and address of a customer. We can easily import this information from databases and applications, revise it, and export it to the same or other databases and applications. Excel creates a map for us automatically when we open the XML data file as a Table. Excel uses every element in the schema, and we have no control over the map or the amount of data that Excel loads into the worksheet. The map becomes part of the workbook, and Excel saves any changes or new data to the workbook in the standard Excel file format (.xlsx). We can only save the workbook as an xlsx file. We can't export the data from the Table, but we can import new or changed data into the list. Case Study 4.2: We have an XML file Salesman Invoice.xml from which we want to create Table. Strategy:
We open Excel and on the File menu, click Open.
In the Files of type list, select XML files (*.xml).
In the Look in list, navigate to the file Salesman Invoice.xml.
Click Open.
Open XML dialog box appears.
Select “As an XML Table” as shown in Fig,1.8.1. and click OK.
Fig. 1.8.1. Open XML Dialog Box
An alert message is seen as shown in Fig click OK.
Fig. 1.8.2. Alert Message
286
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML
Excel creates a new, blank workbook and loads the data into an XML list in that workbook.
We can now Click a column header and use the AutoFilter buttons to sort or filter the data.
We can also use the Table Tools tab to turn on the Total row under Table Style options.
We can use the table options with this Table as shown in Fig 1.8.3
Fig. 1.8.3. Excel sheet created from XML Gist: We have created Excel Sales Table from XML File Commands Learnt: XML to Table
1.9 Creating a Map XML Maps are created from XML Schema. If there is no schema Excel infers one from the structure of the data in the XML file. Schemas don't contain data; the mapped worksheet cells remain empty until data is put into them. Case Study 4.3: We have an XML file Salesman Invoice.xml from which we want to create Map. Strategy:
Open a new Workbook
On the Developer Tab go to XML, and then click Source.
ADVANCED INFORMATION TECHNOLOGY TRAINING
287
ADVANCE MS-EXCEL
Fig. 1.9.1. XML Source in Developer
At the bottom of the XML Source task dialog box, click XML maps.
Fig. 1.9.2. XML Maps Dialog Box
In the XML maps dialog box, click Add. Find the Salesman Invoice.xml file
Click Open.
We get an alert that Excel will create a schema, click OK.
Excel infers a schema for the XML data file, and the XML Source task pane displays that schema for us to use in creating XML map.
Fig. 1.9.3. Mapping Items
288
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML
On the worksheet we start by mapping items that occur only once in the data file. Under Sales ID we drag Sales ID from the task pane to cell E1. Excel surrounds the mapped cell with a Black border, and it displays the Header Options smart tag. Select “Place XML Heading to the left”
When we click another cell, the border becomes thinner and turns blue as shown in Fig. 1.9.3
Now drag Sales_man to cell B1.
We need to also map the data that will occur several times in the worksheet. Drag Row from the XML Source task pane to cell A3. Excel fills cells A3 through C3 with the schema elements located beneath Row. Excel also formats those elements as an XML Table, and an AutoFilter button appears in each cell in row 3 as shown in Fig. 1.9.4.
Fig. 1.9.4. Mapping with XML
Save the workbook.
Gist: We have learnt to create XML Map and create an Excel which can be populated. Commands Learnt: Developer > XML Source
1.10 Rename an XML Map If we ever want to rename an XML Map
Go to XML Source pane Click on XML Maps.
In XML Maps dialog box ADVANCED INFORMATION TECHNOLOGY TRAINING
289
ADVANCE MS-EXCEL
Right Click on the Map which we want to rename and click rename as shown in Fig. 1.10.1
Fig. 1.10.1. Renaming XML Maps
1.11 Import Data into MAP Case Study 4.4: We want to populate this worksheet from the contents of file Salesman Invoice.xml. Strategy: We now have a map, and want to import data from the contents of the XML file.
Select any mapped cell in the worksheet.
On the Developer Tab go to XML, and then click Import
Fig. 1.11.1. Import XML
Import XML dialog box appears.
Browse to the Salesman Invoice.xml file, select it, and then click Import.
Excel loads the XML data into the mapped cells as shown in Fig. 1.11.2.
290
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML
Fig. 1.11.2. Data imported into Mapped Cells
Save the workbook. Excel saves the data with the worksheet.
Go to Developer> XML> Map Properties.
Fig. 1.11.3. Map Properties in XML
Select Append new data to existing XML Table as shown in Fig. 1.11.4.
Fig. 1.11.4. XML Map Properties Dialog Box
Now Excel Table is append able i.e. we can manually add entries.
Gist: We have imported data into Excel from XML Commands Learnt: Developer > XML Map properties
ADVANCED INFORMATION TECHNOLOGY TRAINING
291
ADVANCE MS-EXCEL
1.12 Format the Data and Layout of an XML Table
Select a cell in the XML table.
Go to Developer > XML > Map Properties.
In the XML Map Properties dialog box, We have various options for formatting the data
Fig. 1.12.1. Options in XML Map Properties
Adjust column width To automatically adjust column widths for best fit when XML data is refreshed, select this option. This is the default option.
Preserve column filter To preserve sort order and applied filters when XML data is refreshed, select this option. This is the default option.
Preserve number formatting To preserve number formatting when XML data is refreshed, select this option. This is the default option.
1.13 Add-In SG Data
In the last row press Tab key.
A new row appears at the bottom of the Table.
In the last row we Add next Invoice details in A8 to C8 as shown in Fig. 1.13.1.
292
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML
Fig. 1.13.1. Add-In SG Data
Save the workbook.
1.14 Export Mapped Data After making the changes we can also export the Data. In the export process only the data in the mapped cells of the worksheet are exported.
Select any mapped cell in the practice worksheet.
Go to Developer>XML>Export.
Fig. 1.14.1. Export data
Export XML dialog box appears.
Give the path, enter a name for the exported file, and then click Export.
An XML File is created as shown below and the data we appended manually is appended in XML also as shown in Fig. 1.14.2.
ADVANCED INFORMATION TECHNOLOGY TRAINING
293
ADVANCE MS-EXCEL
Fig. 1.14.2. XML File created after addition of data
The data file is generic XML, so other people or programs can reuse this data.
1.15 Moving Mapped Cells To move mapped cells, we cut and paste just the way we do when moving any other data. Rules to follow when moving mapped cells
To move an XML table e.g Invoices and keep it as a Table, entire set of cells has to be moved together.
If we move individual cells or columns from the list, moved cells will not function as Tables
Maps apply to one worksheet only.
If mapped cells are copied to another worksheet or workbook, recreate the map.
Excel does not export the data that has been moved out of mapped cells.
The export process works on mapped cells only.
In the Salesman Invoice workbook, select the Table that contains the Invoice: cells A3 through C8.
Press CTRL+C to copy the cells.
Select cell A10, press CTRL+V to paste the cells into the new location, and then press ESC.
294
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML
The destination cells are in Table form.
Select and copy cells B3 through C8, the Customer and Amount columns.
Select cell A10, and then paste the copied data.
When we paste the data, Excel doesn't format it as a Table
Fig. 1.15.1. Table formatting removed
1.16 Remove Mapped Cells from a Worksheet Remove mapping leave data
Go to Developer>XML>Source.
In the XML Source task pane, right-click the element that we want to remove and click Remove element as shown in Fig. 1.16.1.
Fig. 1.16.1. Remove Element All the mapped schema elements appear in heavy dark letters. We can one by one remove element in all mapped cells. Alternatively we can remove element in parent element. ADVANCED INFORMATION TECHNOLOGY TRAINING
295
ADVANCE MS-EXCEL
1.17 XML Map Security-Remove Data Source Information An XML map and its data source information are saved with the Excel workbook, not a specific worksheet. This map Information can be seen by someone with a little bit of VBA knowledge. If we want to keep using the map information but remove the potentially sensitive data source information, we can delete the data source definition of the XML schema from the workbook, but still export the XML data,
Go to Developer> XML> Map properties and clearing the Save data source definition in workbook check box as shown in Fig. 1.17.1
Fig. 1.17.1. Clear Save data source
1.18 Refresh Data in an Imported File
On the worksheet, click a mapped cell to select the XML map that we want to refresh.
On the Developer tab, in the XML group, click Refresh Data.
Fig. 1.18.1. Refresh data
If we want to refresh data automatically every time a workbook is opened.
Go To Data Tab >Connections, click the arrow next to Refresh, and then click Connection Properties as shown in Fig. 1.18.2.
296
ADVANCED INFORMATION TECHNOLOGY TRAINING
WORKING WITH XML
Fig. 1.18.2. Automatically refresh data
Under Usage > Refresh control set the preferences like “Refresh data when opening the file”.
1.19 Validate Data against Schema for Import and Export If we want to ensure that the XML data that we are importing or exporting conforms to the XML schema. Excel provides us with a facility to validate data against the XML map when Importing/Exporting data.
Go to Developer> XML> Map properties and click the Validate Data Against Schema For Import And Export check box as shown in Fig. 1.19.1
Fig. 1.19.1. Validating Data against schema
1.20 Summary XML is a great way of Exchanging information between Computer applications Excel is a great tool which allows us to import from or export to XML. In this chapter, we learned how to install XML Tool add-Ins from Microsoft, we learned basics of XML, converting XML to Excel and vice versa, creating an XML data File & Schema file. Create, rename, remove XML Map are important when we want to Add Data from XML and export it to XML. We have also learnt to refresh data from XML manually, or automatically
References [1]
Matthew MacDonald, ‘Excel 2010, THE MISSING MANUAL, O’Reilly Media, Inc, 2010
[2]
http://office.microsoft.com
[3]
http://www.sitepoint.com/really-good-introduction-xml/ ADVANCED INFORMATION TECHNOLOGY TRAINING
297
CHAPTER
2
IMPORTING/EXPORTING DATA
LEARNING OBJECTIVES Introduction Importing data from a text file Exporting data to a text file Saving all or part of a workbook to a static web page Create a Web query
2.1 Introduction As Bank auditors, we find that many Banking applications generate text files in txt or csv format, these files we would need for our data analysis, but Text files do not provide us with data analysis capabilities. Whereas if the same could be converted to Excel File, we could get lot of data analysis capabilities. Excel provides us with these capabilities to import and export data
2.2 Importing Data from Text Files We often get external data that we can import into Excel and analyze. Like data from accounting software, ERP Systems, Banking Applications, databases. At many of these places client would not like to give direct access to databases but he would be comfortable giving us output in text formats. However if we can import these text files, we don't have to type it into Excel saving time and avoiding transcription errors. Text files contain plain text, that is, text without formatting. In text files, data is split by delimiters, characters that separate each field of text. There could be following delimiters:
Tab or some other special character delimited files. A tab usually separates each column.
Comma separated value csv files. A comma (,) usually separates each column. a csv file is a native form to Excel. We notice this by looking at the file icon. It is like a normal one but with a letter 'a' and a comma. If we double-click directly on a csv file, excel will open it
Fixed-length or space delimited files, could be in prn file format. Several spaces usually separate each column.
We can use Microsoft Office Excel to import data from a text file into a worksheet. The Text Import Wizard examines the text file that we are importing and helps us ensure that the data is imported in the way that we want
IMPORTING/EXPORTING DATA Data can be imported in two different ways, will depend on
Whether data is static ie we don’t have to change it in future or Whether data will change/revise in future depending upon external data source.
Both the methods start in different ways but the last steps are same. The trick to importing data from a Word or text file into Excel is to use the Excel Text Import Wizard which imports the text file in 3 easy steps. Step 1- Wizard determines whether data is Delimited or Fixed width, the other usual option allows us to start the import at a certain row. Step 2-We can define Delimiters or in case of fixed width this step allows us to click at the fixed widths of your data to set the delimiting 'bars'. Step 3- We can set the columns as certain data types ie text or Date etc. or not import at all. We can import or export up to 1,048,576 rows and 16,384 columns in Excel. Case Study 2.1: While auditing a bank, we want to check for all those Bank limits where validity of sanction has expired. We tell the auditee to provide us data relating to expiry dates of limits. To preserve data integrity the auditee does not give us direct access to the database but is willing to provide us any reports we desire in txt format, further he is willing to provide us text reports in delimiters of our choice, he provides us Limit Expiry list in Tab delimited form, csv, fixed length format as shown in Fig. 2.1.1
Tab Delimited
Comma Separated Values (csv)
Fixed Length delimited Fig. 2.2.1. Limit Expiry Report
299
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCE MS-EXCEL Strategy: We can convert these files to Excel files for easy data analysis. We will try to import all the three formats mentioned above and also try to import it with facility that we can revise it later on with changed data.
2.2.1 Import of Text File not to be changed
Open a new workbook, on the File menu, click Open.
In the bottom of the Open dialog box, in the Files of type list, select All files or Text Files.
Fig. 2.2.2. File selection area in open dialog box
In the File Name list at the bottom of the dialog box, browse to the location where we stored the expired limits Tab.txt file we have received from auditee.
Select the file, and then click Open.
The Text Import Wizard opens.
In the step 1 of 3, we select the correct delimiter to split the text into the proper columns. In our case since the file we have is tab delimited we select Delimited - characters such as commas or tabs separate each field.
Fig. 2.2.3. Step 1 of Text Import Wizard 300
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORTING/EXPORTING DATA
If we look at the preview at the bottom of the wizard. On the first row at the top of the preview we find the name of bank and in second row is the title of report.
It is only from 3rd row that data starts and delimiters are there. Sometimes a file can contain more than one delimiter in a row.
If we want to leave the name of bank and title of report we can select Start import at row to start at 3. Row 3 in this file contains the headings "Account Number”, "Acct Name," etc. which could be useful since they provide column headers.
Click Next.
In the step 2 of 3 of the wizard, we select the delimiters contained in the text file. Since our file is tab delimited file Tab is already selected for us.
Fig. 2.2.4. Step 2 of Text Import Wizard “Text qualifier”- We can select double quotation marks ("), single quotation mark ('), or none, or we can leave this option alone. Text qualifiers (" or ') are sometimes used in text files to indicate the beginning and end of text strings. We can see in the preview if qualifiers are used. For example, double quotation marks around the Sanction limit on our case this tells excel that these are text strings. If the file contained more than one type of delimiter (commas or semicolons, for example), we would select them all.
301
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCE MS-EXCEL Further we could have more than one delimiters between two data, we need to select “Treat consecutive delimiters as one” check box.
We see neatly aligned Columns. Click Next.
In the step 3 of 3 of the wizard, allows you to set the columns as certain data types or not import at all as shown in Fig. 2.2.5
Fig. 2.2.5. Step 3 of Text Import Wizard We can make formatting changes if necessary. Excel automatically formats each column as General. Numeric values are converted to numbers, date values are converted to dates, and all remaining values are converted to text. However, we can make changes to the format of columns by selecting a column and then selecting an option under Column data format. For example, In the above case we could select date for column “sanction date” and “expiry date” and select an appropriate Date mask on our case DMY. We can also skip a column instead of importing it by selecting the Do not import column option.
Click Finish.
We now need to set the layout as some of the columns are not wide enough to display the content. Some data is either cut off, as in the headings in column A etc where the last few letters are missing, or where we see the error value ###### in column D. as shown in Fig. 2.2.6.
302
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORTING/EXPORTING DATA
Fig. 2.2.6. Txt File converted to Excel File
Select Top left corner, Move the pointer over the column heading between columns A and B until the pointer changes to a dark cross with two arrow points. Double-click the right column boundary of column B. all the columns will expand to auto fit the data.
Click Save on the File menu. We could see a message that says that the file may contain features that are not compatible with Text (Tab delimited) format.
If we click Yes, this file will be saved as a .txt file. If we click No, the file will be saved as an Excel workbook (.xlsx).
Since we want a file with all excel features we Click No.result is as shown in Fig. 2.2.7.
Fig. 2.2.7. Resultant Excel File
303
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCE MS-EXCEL
2.2.2 Importing a Fixed Width File
If the file to be imported was fixed width then in Step 1, we select Fixed width as shown in Fig. 2.2.8.
Fig. 2.2.8. Step 1 of Text Import Wizard-Fixed Width
After clicking next, in Step 2 of 3 We can split columns by clicking to fix column boundaries if they are not correct. We can see in the preview how the columns look as shown in Fig. 2.2.9
Fig. 2.2.9. Step 2 of Text Import Wizard-Fixed Width 304
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORTING/EXPORTING DATA
In the wizard's step 3 of 3, we can make formatting changes if necessary. Excel automatically formats each column as General. Numeric values are converted to numbers, date values are converted to dates, and all remaining values are converted to text.
We can also skip a column instead of importing it by selecting the Do not import column option.
Click save and save it as xlsx File.
Fig. 2.2.10. Resultant Excel File-Fixed width
2.2.3 Importing A Text File That We Can Change/Revise
On the Data tab, go to Get External Data, and then click From Text.
Fig. 2.2.11. Get External Data from Text
In the bottom of the Import Text File dialog box, in the Files of type list, select Text Files.
In the File Name list at the bottom of the dialog box, browse to the location where we stored the expired limits Tab.txt file we have received from auditee.
Select the file, and then click Import.
The Text Import Wizard opens.
305
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCE MS-EXCEL
Rest of the steps are Steps 6 to 14 above.
After which import data dialog box appears where we have the option of having the data in existing worksheet or in new worksheet as shown in Fig. 2.2.12.
Fig. 2.2.12. Import data Dialog Box
Under properties on Import dialog box we have various options as shown in Fig. 2.2.13.
Fig. 2.2.13. External data Dialog Box
Click OK and the file is imported as Excel sheet.
In Connections group we can use Refresh All to update the data in Excel if the external data is updated.
2.2.4 Update the Data
In cell C6, delete the figure 32,00,000.
Now the external data and the data in Excel are different.
On the Data tab > Connections, click Refresh all.
It asks us to select source, once we select “expired limits Tab.txt”
We see that data has been refreshed from txt file and the figure 32,00,000 is in the cell again.
306
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORTING/EXPORTING DATA Gist: We have imported Text files to Excel both in static format as well as dynamic format Commands Learnt: Import Text Wizard.
2.3 Exporting Data to A Text File We can convert any Excel worksheet to a text file by using the Save As command.
Click the File Tab, and then click Save As.
The Save As dialog box appears.
In the Save as type box, choose the text file format for the worksheet. Different formats will give different results
.txt - Text (Tab delimited) This file format (.txt) saves only the text and values as they are displayed in cells of the active worksheet. Columns of data are separated by tab characters, and each row of data ends in a carriage return. If a cell contains a comma, the cell contents are enclosed in double quotation marks. If the data contains a quotation mark, double quotation marks will replace the quotation mark, and the cell contents are also enclosed in double quotation marks.
.csv- CSV (Comma delimited) This file format (.csv) saves only the text and values as they are displayed in cells of the active worksheet. All rows and all characters in each cell are saved. Columns of data are separated by commas, and each row of data ends in a carriage return. If a cell contains a comma, the cell contents are enclosed in double quotation marks.
.prn- Fixed Width Text This file format (.prn) saves only the text and values as they are displayed in cells of the active worksheet. For best results first format the worksheet in Courier New font and save as .prn file
A dialog box appears, reminding us that only the current worksheet will be saved to the new file
A second dialog box appears, reminding us that our worksheet may contain features that are not supported by text file formats.
If we are interested only in saving the worksheet data into the new text file, click Yes.
The file is now exported or converted as text file.
2.4 SAVING ALL OR PART OF A WORKBOOK TO A STATIC WEB PAGE We can save an entire workbook, including tabs for navigating worksheets, or portions of a workbook, such as a range or chart, to a static Web page so that users can view our Microsoft Office Excel data on the World Wide Web.
307
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCE MS-EXCEL Web Page and Single File Web Page- Web Page file formats (.htm, .html), Single File Web Page file formats (.mht, .mhtml) can be used for exporting Excel data. Case study 2.2: We have an Excel File “Expired Limit Import.xlsx” which we want to save/Publish on a static webpage. Strategy
On the File tab, click Save As.
The Save As dialog box is displayed.
In the list box, do one of the following:
To save to a Web page and create supporting files and folders, select Web Page (*.htm; *.html).
To save to a Single File Web page with supporting files embedded in the Web page, select Single File Web Page (*.mht; *.mhl)
To save the entire workbook, including tabs for navigating each worksheet in the workbook, click Entire Workbook.
Fig. 2.2.14. Save as Dialog Box
To add a title that is centered over the selection and in the title bar of the browser, click Change Title. Type the title that we want, and then click OK.
Click Publish.
The Publish as Web Page dialog box is displayed.
308
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORTING/EXPORTING DATA
Fig. 2.2.15. Publish as web page dialog Box Under Item to publish in the Choose box, select one of the following:
Entire workbook Select Entire workbook. The entire workbook is saved, including tabs that a user can use to navigate to each worksheet.
Items Select Items on Sheet name, and then select the item that we want to save, such as a PivotTable report or a chart. Items do not include ranges of cells.
Ranges of cells Select Range of cells and then, if the selection box does not contain the range that we want, click the worksheet select a range of cells from the Excel workbook. Select the Auto Republish every time this workbook is saved check box, if we want to make changes in the workbook later and want to automatically republish the items each time that the workbook is saved. To view the Web page in the browser after saving it, select the Open published Web page in browser check box
309
To change Web page options, click the arrow next to Tools, and then click Web Options we see lots of options as shown in Fig. 2.2.16.
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCE MS-EXCEL
Fig. 2.2.16. Web Options
Click save an dialog box appears as shown in Fig. 2.2.17. Confirming about Auto Republish options.
Fig. 2.2.17: Auto Republish feature
Click OK.
We see that html file along with supporting folder are saved as shown in Fig. 2.2.18.
Fig. 2.2.18. Webpage & Files
310
And we have a webpage as shown in Fig. 2.2.19.
ADVANCED INFORMATION TECHNOLOGY TRAINING
IMPORTING/EXPORTING DATA
Fig. 2.2.19. Webpage of Expired Limits
2.5
Create A Web Query
Web queries allow us to query data from a specific World Wide Web, Internet, or intranet site and retrieve the information directly into a Microsoft Excel worksheet. We now want to create a web query from the web page we have in Fig.
Open the web page expired limits,
Select the data and press the Ctrl + C combination.
Open a new Excel workbook and activate the cell where we wish to insert the data.
Click the Paste dropdown button on the Home Ribbon as shown in Fig. 2.2.20.
Fig. 2.2.20. Paste Special option
311
Click Refreshable Web Query. A New Web Query dialog box appears as shown in Fig. 2.2.21.
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCE MS-EXCEL
Fig. 2.2.21. New Web Query
Click the Yellow Arrow next to the information we want to import.
Click Import.
The web query is created in Excel.
Fig. 2.2.22. Web Query in Excel Gist: We have created Web Page & Web Query in from Excel. Commands Learnt: Save as web page
Summary In this chapter we have learnt It is easy to take content/data from another non-Office application and bring it into an Excel, we learned how to convert Text file in Tab delimited or csv or Fixed width files to Excel file. We have also learnt to import external data as refreshable/ changing dynamic data Finally, we learned to use to create a static web page and web query from Excel data
References [1]
Laurie Ulrich Fuller et al, ‘Picture Yourself Learning Microsoft Excel 2010’ Cengage Learning 2011
[2] 312
http://office.microsoft.com/en-us/excel-help/redir/AM010338542.aspx?CTT=5&origin=HA010338210 ADVANCED INFORMATION TECHNOLOGY TRAINING
CHAPTER
3
ADVANCES IN MACROS
LEARNING OBJECTIVES To gain understanding of Macros To understand Recording of Macros To understand Assigning a button to Macros To understand Absolute & Relative references in Macros
3.1 Introduction We all want shortcuts and to avoid the chore of doing monotonous work like data entry or some formatting which we want done every time. Excel offers us excellent options to automate in the form of Macros which are basically small programs which automatically perform repetitious steps.
3.2 What is A Macro Programming of Macros is done in programming Language VBA (Visual Basic for Applications) but we can use Macros even if we do not know VBA since Excel gives us a wonderful tool in the form of Macro Recorder. A macro records our mouse clicks and keystrokes while we work and play them back later Macros can be written in two ways
Writing a Macro using VBA Code
Recording a macro using Excel Macro recorder
3.3 Recording a Macro If we have to store Macros it is not possible in .xlsx files. Fortunately excel has a file extension .xlsm which are macro enabled workbooks. Excel gives macro-enabled workbooks a different icon, with a superimposed exclamation mark.
This icon enables us to recognize a macro-enabled workbook.
Some tips to record a macro
Excel records every keystroke & every command we run, so something we don’t want should not be done while recording Macro.
We don’t need to work fast, i.e., Macro just records our actions, so if we are just browsing, that is not recorded it is only specific actions which get recorded.
ADVANCE MS-EXCEL
Try to be generic, since we’d want that macro to run in various situations & scenarios.
Enabling Macro Security
On the Developer tab, click Macro Security in the Code group.
The Security dialog appears.
In the Security dialog, change the Macro Settings to Disable All Macros with Notification.
With this setting, Excel alerts us whenever we open a workbook that has macros attached.
When we open a document and get the warning that the document has macros attached, if this is a document that we wrote and we expect macros to be there, click Enable Content to enable the macros
Where Macros Are Stored Macros can be stored in either of two locations, as follows:
The workbook we are using, or
Our Personal Macro Workbook (which by default is hidden from view)
If our macro applies to all workbooks, then store it in the Personal Macro Workbook so it will always be available in all of our Excel workbooks; otherwise we store it in our current workbook Case Study 3.1: CA P C Gupta gives us a boring routine in Excel, he says when analyzing Debtors List in excel sheet wherever we find an aberration which needs to be investigated further, we are to highlight the cell. To highlight, Font in bold, the cell fill color has to be changed to pink, font color to blue and insert border for the cell. It is really a chore to do it every time. We want to automate this routine and assign a shortcut key for it.
Fig. 3.3.1. Debtors Data 314
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCES IN MACROS Strategy: We can automate this boring task using Macros in Excel We can record a Macro in 3 different ways
In Excel 2010 Macros are in Developer Tab, which is not there by default.
To activate it we have to go to File> Options as shown in Fig. 3.3.2
Fig 3.3.2. Options in File Tab
Under Options > Customize the Ribbon > On the right of the window, a large box lists all the tabs that are currently shown in the ribbon. Near the bottom, we see an unchecked item named Developer as shown in Fig. 3.3.3. To show the Developer tab, check this box, and then click OK.
Fig 3.3.3. Customize ribbon in options ADVANCED INFORMATION TECHNOLOGY TRAINING
315
ADVANCE MS-EXCEL
Macros are under Developer tab as shown in Fig. 3.3.4
Fig. 3.3.4: Macros in Developer tab
Recording a Macros is also available in View> Macros as shown in Fig. 3.2.5
Fig. 3.3.5: Macros under view
There is one more option to record macro in status bar as shown in Fig. 3.3.6
Fig. 3.3.6: Record a macro in status Bar
316
Using any of the above methods we start recoding a Macro, a macro dialog box appears as shown in Fig. 3.3.7
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCES IN MACROS
Fig. 3.3.7: Record a macro in status Bar
We give macro a name let’s say “PinkHighlight” , we can also attach a shortcut key to it, since most of Ctrl + short cut keys are already reserved it is better to go for Ctrl+Shift+. In this case we select “Ctrl+Shift+P” just a mnemonic since we want to go for pink highlight. Further Macro can be stored in:
This Workbook. If we choose this option, Excel stores our macro in the current workbook. Remember, we need to save this workbook as a macro-enabled .xlsm file or a binary .xlsb file, or we’ll lose our macros.
New Workbook. If we choose this option, Excel automatically creates a new workbook (which it opens in a separate window) and stores our macro there.
Personal Macro Workbook. If we choose this option, Excel stores our macro in a special hidden workbook named Personal.xlsb. The Personal.xlsb workbook opens automatically whenever we start Excel (although it remains hidden), so macros in this workbook are always available no matter what workbook we’re using.
ADVANCED INFORMATION TECHNOLOGY TRAINING
317
ADVANCE MS-EXCEL
We store the macro in personal workbook since we want it to be available for all workbooks.
We also give the macro a description “Macro to highlight in pink”.
As we begin recording we see that record macro button has changed to “stop recording” in both header & status bar as shown in Fig. 3.3.8
Fig. 3.3.8: Stop recording in developer tab & status Bar
Now we perform the recording of action
we select B10 which we need to highlight in pink and
go through the desired steps on Home Tab first we make the font Bold,
next we change the font colour to Blue,
Change the fill to Pink &
Insert a border for the cell.
We now click the stop recording Button
Our macro is now ready, to execute on any cell press Ctrl+Shift+P and we find that the cell gets the desired formatting
Fig. 3.3.9. Macro is executed on pressing Ctrl+Shift+P
318
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCES IN MACROS Gist: We have recorded a macro to give the desired pink highlighting to a cell to Excel both in static format as well as dynamic format Commands Learnt: Record a Macro
3.4
Assigning a Button to Macro
We have seen that Macros make our repetitive job a lot easier to perform but it would be extremely useful if we can run macro with a simple click on button, rather than running it manually. By creating macro-buttons we will be able to associate macros with buttons, and show them on the worksheet for performing different tasks we have recorded with macro. Excel enables us to create custom buttons to link macros with them, the following case study will elaborate how to create macros and associate buttons with them. Case Study 3.2: In case study 6.1 we wish to assign a button in Quick Access Toolbar & also make a button on the worksheet for one touch macro execution. Strategy: We can assign Buttons for macros in many ways we will discuss two of them. Button on Quick Access Toolbar (QAT)
Right click on Quick Access Toolbar (QAT) and select the option “Customize Quick Access Toolbar” as shown in Fig. 3.4.1
Fig. 3.4.1. Customize Quick Access Toolbar
Select the “Macros” under “Choose commands from”
Fig. 3.4.2. Select macros ADVANCED INFORMATION TECHNOLOGY TRAINING
319
ADVANCE MS-EXCEL
Under Macros select the Macro we wish to add to QAT in this case “PERSONAL.XLSB!PinkHighlight” >add as shown in Fig. 3.4.3
Fig. 3.4.3. Select PERSONAL.XLSB!PinkHighlight
Select PERSONAL.XLSB!PinkHighlight in the right pane & click Modify we see lot of symbols which we can assign any pink symbol to make it easy for us to recall and also change the display name to Pink Highlight and click OK as shown in Fig. 3.4.4
Fig. 3.4.4. Modify Button
We see that a new Button for pink highlighting is added to our toolbar.
Fig. 3.4.5. Pink highlight Button on QAT 320
By clicking this button in QAT we can run this macro. ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCES IN MACROS
Another button we can have on the sheet itself.
We go to Insert>Shapes> select a shape, let’s say “5-Pointed Star”
Fig. 3.4.6. Select Shapes from Insert
Next we go to shape fill & select a color, we select pink since we want to use it for pink highlighting.
Fig. 3.4.7. Pink highlight Button on QAT
We also go to txt box & give the star a caption “Pink”
We then right click on the star & select “Assign Macro”
ADVANCED INFORMATION TECHNOLOGY TRAINING
321
ADVANCE MS-EXCEL
Fig. 3.4.8. Right click & select ”Assign Macros”
In the Assign Macro dialog box we select macro “PERSONAL.XLSB!PinkHighlight”
Fig. 3.4.9: Assign Macro Dialog Box 322
Macro is now assigned to the shape, clicking on the shape macro in executed. ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCES IN MACROS
Fig. 3.4.10: Pink highlight Button on QAT Gist: We have assigned a button in QAT to macro & also assigned a shape to it. Commands Learnt: Assign a button
3.5
Absolute and Relative Referencing
Absolute reference mode. In absolute reference mode, Excel stores the absolute references for the cells that we’re modifying. Relative reference mode. In relative reference mode, Excel tracks how far we move from our starting position.
Relative Referencing By default, Excel Macro Recorder records our absolute steps. Let’s suppose we want to move from cell A1 to B1 after performing an action, we will press the Right Arrow key, but Excel will not record this key, instead it will only record the movement to cell B1. Now let’s suppose we have recorded the actions and are to perform it in cell C1, when we run the Macro, a line of Macro will be executed and then cell B1 will be selected instead of selecting cell D1 (which is to the right of C1). Excel records the movement to cell B1 instead of recording every action (keystroke). If we want Excel to record relatively, so that Excel moves to the right cell instead of selecting cell B1, we will have to enable Relative References. It can be switched on from the Macros menu just below the Start/Stop Recording option. Case Study 3.3: We have to include a debtor list with our balance sheet auditee has given us a list of debtors with Name & City underneath it & Balance in the next cell as shown in Fig. 3.3.1 , however we want a list with 3 columns Name, City & Balance. To convert it we have to follow the boring routine of cut, paste & delete row for each debtor. We however want to automate this task.
ADVANCED INFORMATION TECHNOLOGY TRAINING
323
ADVANCE MS-EXCEL
Fig. 3.5.1. Debtors Data Strategy: We can automate this boring task using Macros in Excel
We first insert a Column after A and name it city.
Go to Developer > Record Macro a Record Macro Dialog Box appears as shown in Fig. 3.5.2
Fig. 3.5.2. Record Macro
Select a name for the Macro “Singlerow”,
Assign a shortcut key “Ctrl+Shift+R” and
Store the macro in” this workbook “since this macro would be used by us only once in this specific workbook.
324
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCES IN MACROS
Click Ok
Now the recording starts and all our steps would be recorded in the form of Macro.
We perform the steps as shown in Fig. 3.3.3
ADVANCED INFORMATION TECHNOLOGY TRAINING
325
ADVANCE MS-EXCEL
Fig. 3.5.3. Steps to record a Macro
We start
at Cell A2
Move to Cell A3.
Cut Cell A3 and paste to Cell B2.
Delete Rows 3 through 4.
Go to Cell A3
Stop Recording.
Our Macro is now recorded.
We can execute the macro by pressing Ctrl+Shift+R.
Let’s try executing the Macro!!!!!!!!!
Lo and Behold what has happened the company name from A3 has shifted to cell B2 and overwritten city.
Fig. 3.5.4. Data destroyed
Executing Macro once more and we see Excel eating our cells & destroying Data.
What’s happened?
This has happened because by default macro records our actions literally and foolishly executes them ie it again goes to Cell A2, Move to Cell A3, Cut Cell A3 ie “XYZ LLP” and paste to Cell B2 overwriting city “New Delhi”, Delete Rows 3 through 4, Go to Cell A3.
And the result is absurdity we see above.
326
ADVANCED INFORMATION TECHNOLOGY TRAINING
ADVANCES IN MACROS
Solution to the problem is in a button on developer tab “Use Relative References” as shown in Fig. 3.3.5.
Fig. 3.5.5. Use Relative References
Now before starting recording of the above macro we should have activated “Use Relative References” and proceeded to record the Macro.
To remove the above Macro we go Developer > Macros.
Fig. 3.5.6. Macro under developer
We can see the Macro Dialog Box, Select macro Singlerow and click delete the Macro will be deleted.
Fig. 3.5.7: Delete Macro
To again start recording a Macro we first Activate “Use Relative References” and we see that the option has changed in color.
Then we start recording Macros, to record Macro We repeat steps 9 enumerated above. ADVANCED INFORMATION TECHNOLOGY TRAINING
327
ADVANCE MS-EXCEL
Our Macro is now recorded.
We try executing it & press Ctrl+Shift+R.
The result is perfect something we desired.
Basically by using “Use Relative References” we are telling Excel
Move down one cell,
Cut the Value
Move one cell up, one to the right and paste the value.
Move two cells left.
Move Two cells Under select the two rows
Delete the rows
Move one cell below
We execute the macro a number of times and our sheet gets into the desired shape i.e. we have Name, City and Balance in a single Row as shown in Fig. 3.3.8.
Fig. 3.5.8. Resultant Sheet Gist: We have arranged Name, City & Balance in single row using a Macro Commands Learnt: Use Relative References in Macros
Summary In this chapter we have learned it is easy to automate Excel to do repetitive things through Macros, we learned how to record a Macro. We have also learned to assign buttons to Macros Finally, we learned to use relative References so that Macros don’t do foolish things.
References [1]
328
Greg Harvey, ‘Excel 2010 For Dummies’, Wiley Publishing, Inc., Indianapolis, Indiana, 2010.
ADVANCED INFORMATION TECHNOLOGY TRAINING
CHAPTER
4
APPLIED FINANCIAL ANALYSIS
LEARNING OBJECTIVES To understand Financial Analysis To understand Du-Pont Analysis To understand Leasing decisions To understand Financial Shenanigans To understand Equity Analysis To learn Chart creation Scenarios and Case Studies
4.0 Introduction One of the most important features of excel is its number crunching ability. This is the reason it is used in almost every organization. Most Finance management or accounting packages allow us to export data into Excel format. Thus data analysis and reporting becomes an easier task. Excel allows us to use various functions and even simple mathematical calculations can be performed for financial analysis, equity analysis, leasing decisions and the list goes on. However before we proceed, we need to know certain basic things about excel formulae:
4.1.1. Elements of a Formula A Formula can have the following elements:
Arithmetic Operators: These include symbols such as + (for addition) and / (for division)
Conditional Operators: These include symbols such as > (greater than) ; <= ( less than equalto); <> (not equal to)
Cell References: These include references such as C4, =Sheet2!C4 (reference to other sheets)or references to other workbooks.
Range References: These include references such as A1:A4, A1:D1, A1:D6
Named References: These are named ranges or references created by the user to refer to aparticular range of cells. Ex: Range name “Data” referring to a range “A1:D100”
Values or Strings: These are values such as 10 or10.5 (values) or “State wise Sales” (String).
Strings are to be always enclosed in double quotes when used in a formula.
ADVANCE MS-EXCEL
Worksheet functions: A formula may consist of multiple functions and each function shall haveits own set of arguments and parameters.
Parentheses: Every formula has its own set of arguments which are written in parentheses.Parentheses are also used to change the order of calculation.
Note:Excel colours the range addresses and the cells that you enter in a formula. This helps as a visual aid to spot the range used in the formula to either understand its working or to spot errors.
4.1.2. What is a Function? A worksheet function is a built in tool that you use in a formula. Worksheet functions allow you to perform calculations or operations that would otherwise be too cumbersome or impossible altogether.
4.1.3. Arguments of a Function A function may have:
No arguments Ex: =TODAY()
TODAY function gives you system date which changes daily. This function doesn’t require an argument.
One argument Ex: =ABS(-4)
ABS function gives you absolute value of a number, number without its sign. This function accepts only one argument.
A fixed number of arguments Ex: =MOD(100,3)
MOD function returns the remainder after a number is divided by a divisor. It mandatorily requires two arguments: number and divisor.
Optional arguments
Ex: =INDEX (Salesdata, 5) INDEX function returns value from a given data range based on row and column. However in this function, “column number” is optional thus the function will work even without column number provided appropriate data has been selected.
4.1.4. Function Categories Following function categories are available in excel: Financial Math & Trig Lookup & Reference Text Information & Compatibility Engineering 330
Date & Time Statistical Database Logical User defined Cube
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
4.1.5. Show Formula Mode You can often understand an unfamiliar workbook by displaying the formulas rather than the results of the formulas. To toggle the display of formulas, choose Formulas > Formula Auditing > Show Formulas. You can also use Ctrl+` ( ~ the accent grave key, usually located above the Tab key) to toggle between Formula view and Normal view.
4.2
Financial Analysis
Usually potential investors analyze financial statements of companies they want to invest in. This is because financial statements reveal about the current and future financial condition of the company. Financial analysis often involves comparison between companies in the same industry, companies against external benchmarks and analysis of internal performance trends. Analysis also includes forecast based on historical performance. Before we move into the analytics we need to understand the balance sheet.
4.2.1. Understanding the balance sheet. A Balance Sheet is a summary of the financial position of a business at a specific point in time, showing all assets, liabilities, and equity. It represents the accounting equation: assets equals liabilities plus shareholders’ equity. Assets are the means utilized to operate the company and are balanced by a company’s financial obligations plus equity investment brought into the business and retained earnings. Here is a very simple example: For your new business, you want to buy a small office. You have ` 5 lakhs which you pay as down payment for office. Additional ` 20 lakhs you borrowed is your liability. (Assume you have borrowed from friends and relatives as interest-free loan.) as shown in Fig 4.2.1-1
Financial Obligation
Value
Assets Office
25,00,000
Total Assets
25,00,000
Liabilities Loans Outstanding Owner’s Equity Total Liabilities and Equity
20,00,000 5,00,000 25,00,000
Fig 4.2.1-1 Simple Balance sheet
ADVANCED INFORMATION TECHNOLOGY TRAINING
331
ADVANCE MS-EXCEL A standard balance sheet comprises of following items as shown in Fig 4.2.1-2: Asset & Liability Categories
Examples and Explanation
Assets Current Assets
Examples include cash, marketable securities, accounts receivable and prepaid expenses.
Long term investments and other assets
Examples include investments in other companies.
Property, Plant and Equipment
Examples include fixed asset and machinery
Intangible assets
Examples include goodwill and patents
Total Assets
Total of current long term and intangible assets
Liabilities and Equity Current Liabilities
Examples include accounts payable and short term debt
Long term Liabilities
Long term debts
Total Liabilities
Total of current and long term liabilities
Equity Retained Earnings
Companies cumulative net income or loss
Owner Equity
Examples include owner’s contribution and investments.
Total Equity
Total of earnings and owner equity
Total liabilities and equity
Total of liabilities and equity
Fig 4.2.1-2 Standard balance sheet items 4.2.2. Financial Ratios – An introduction Financial analysts have a wide array of analysis tools at their disposal. Financial ratios are fundamental analytical tools for interpreting financial statements. Financial ratio analysis relates items in the financial statements in a manner that drives out performance information about the company. The following example shall better illustrate the significance of ratios. Ex: Revenue of Company A is ` 50,000/- and Company B is ` 40,000/-. Which company is better?The obvious answer based on earnings is that Company A is better because it earns more. Now, suppose the capital employed by Company A is Rs 4, 00,000/- and Company B is ` 3, 00,000/-. Based on this new information we shall derive Profit as a % of Capital Employed Company A = (50,000 / 4, 00,000)*100 = 12.50% Company B = (40,000 / 3, 00,000)*100 = 13.33% Company B is better than Company A based on the above ratio. 332
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS Thus ratios help us to convert figures into logical percentages which can then be compared with ratios from some other companies or a company’s own past performance and appropriate conclusions can be drawn.
4.2.3. Various Ratios & Case Study There are various types of ratios available to an analyst. In this section we shall cover a few of them with the help of the following case study as shown in given Figures:
Fig 4.2.3-1 Case Study – Balance Sheet
Fig 4.2.3-2 Case Study – Income Statement ADVANCED INFORMATION TECHNOLOGY TRAINING
333
ADVANCE MS-EXCEL
Liquidity Ratios These ratios shows the ability of a company to pay its current financial obligations. Company should not be selling its assets at a loss to meet its financial obligations. In a worst scenario company will be forced into liquidation.
Current Ratio (CR)
It is a measure of company’s ability to meet its short term requirements.
It indicates whether current liabilities are adequately covered by current assets.
It measures safety margin available for short term creditors.
CR = Current Assets / Current Liabilities
If Net Working Capital is to be positive, CR > 1
Higher ratio ensures firm does not face problems in meeting increased working capital requirements.
Low ratio implies repeated withdrawals from bank to meet liquidity requirements.
High CR as compared to other firms implies advantage of lower interest rates on loans.
Fig 4.2.3-3 Current Ratio
Acid Test / Quick Ratio (QR)
Used to examine whether firm has adequate cash or cash equivalents to meet current obligations without resorting to liquidating non cash assets such as inventories
Measures position of liquidity at a point of time
QR = Quick Assets / Current Liabilities
Quick assets = Current assets – (inventories + prepaid expenses) = 681–(355+64) = 262
Current liabilities = 399
QR = 262/399 = 0.66
As a thumb rule ideal QR = 1; should not be less than 1
334
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
Fig 4.2.3-4 Quick Ratio
Leverage / Solvency Ratios These ratios show dependency of a firm on outside long term finance. They show long term financial solvency & measures firm’s ability to pay interest & principle regularly when due. To assess extent to which the firm borrowed money vis-à-vis funds supplied by owners. Companies whose EBIT is less than Interest payments are risky
Debt – Equity Ratio:
It measures relative proportion of debt & equity in financing assets of a firm.
Company can have good current ratio and liquidity position, however liquidity may have come from long term borrowed funds, the repayment of which along with interest will put liquidity under pressure.
DER = Long term debt / Shareholders funds.
Creditors would like this ratio to be low.
Lower ratio implies larger credit cushion.
Debt (loans) = Secure loans + Unsecure loans = 151+30=181
Shareholders’ funds = (equity + preference capital + reserves & surplus – fictitious assets & accumulated losses not written off ) = 120+50+215 = 385
DER = 181/385 = 0.47 = (0.47:1)
Creditors are providing Rs 0.47 financing for each rupee provided by shareholders as shown in Fig 4.2.3-5.
Fig 4.2.3-5 Debt-Equity Ratio ADVANCED INFORMATION TECHNOLOGY TRAINING
335
ADVANCE MS-EXCEL
Debt – Total Fund Ratio:
DTF ratio= Long term debt / Total fund
Debt (long term) = 181
Total funds (debt + shareholders’ funds) = 181+(170+215-35) = 531
DTF ratio = 181/531 = 0.34
34% of the firms funds are debt (of various types) remaining 66% is financed by owners/ shareholders.
Higher the debt - total funds ratio, greater the financial risk as shown in Fig 4.2.3-6
Fig 4.2.3-6 Debt Total Fund Ratio
Debt – Assets Ratio:
Debt - Assets ratio = Debt / Net assets
Debt = 181
Net assets (less fictitious assets & losses) = 930
Ratio = 181/930 = 0.19
19% of the firm’s assets are financed with debt (of various types).
Shows coverage provided by the assets to total debt as shown In Fig 4.2.3-7.
Fig 4.2.3-7 Debt Asset Ratio
Interest Coverage Ratio:
This ratio shows ability of company to pay back long term loans along with interest or other charges from generation of profit from its operations
Interest coverage ratio = EBIT / Debt interest
336
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
EBIT = 143
Interest = 29+4 = 33
Ratio = 143/33=4.33
EBIT should be 6 – 7 times of debt interest
Fig 4.2.3-8 Interest Coverage Ratio Liability Coverage Ratio (LCR):
Calculated to determine time a company would take to pay off all its liabilities from internally generated funds.
Assumes that liabilities will not be liquidated from additional borrowings or from sale of assets.
LCR = internally generated funds / Total liabilities.
Internally gen funds = Equity + Preference + Reserves & Surplus = 385
Total liabilities = 965
LCR = 385/965 = 0.399
Firm will take 2.5 years (1/.399) to repay all its liabilities
Fig 4.2.3-9 Liability Coverage Ratio Turnover / Activity Ratios Allows to examine whether total amount of each type of asset a company owns is reasonable, too high or too low in light of current and forecast operating needs. In order to purchase / acquire assets, companies need to borrow or obtain Capital from elsewhere:
More assets acquired implies high interest and low profits.
Lesser assets implies operations not as efficient as possible.
Activity turn over ratios used to assess efficiency with which company is utilizing its assets.
Relates to level of activity represented by sales or cost of goods sold ADVANCED INFORMATION TECHNOLOGY TRAINING
337
ADVANCE MS-EXCEL Inventory turnover ratio:
Measures No of times inventory turned over in a year OR No of days of inventory held by company to sales
Times Inventory turned over = Net sales
OR
COGS
.
Average inventory Average stock Inventory measured in days of sale = 365 x Average inventory
Net Sales
Ratio = 904 / 355 = 2.54 times
This ratio indicates that inventory has turned over 2.54 times in a year.
Inventory in days = (355 x 365) / 904 = 143.33 days
This ratio indicates that company has enough inventory to support 143 days (almost 5 months) sales as show in given Figures.
Fig 4.2.3-10(A) Inventory Turnover Ratio
Fig 4.2.3-10(B) Inventory Turnover Ratio
Average collection period (ACP)
It represents duration a company must wait after making sales, before it actually receives cash from its customers
Average collection period =
This ratio is used to assess credit policy of firm.
It enables to effectively manage their credit.
If ratio is too high it means company is facing difficulties in collecting debts.
338
Average receivables × 365 Average receivables OR Sales Average sales per day
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
If the ratio is too low means the company is having restrictive credit policy
ACP = (189 x 365) / 904 = 76 days
Fig 4.2.3-11 Average Collection Period
Fixed assets turnover ratio (FATR):
It helps to measure effective utilization of fixed assets by company.
It is used to compare fixed assets utilization of two firms.
High ratio usually indicates better asset utilization.
Sometimes this ratio may be too high if assets are old or the ratio maybe too low if capital assets are procured recently.
FATR = Net Sales ( or COGS) / Fixed Assets = 904 / 229 = 3.95
Fig 4.2.3-12 Fixed Assets Turnover Ratio
Profitability Ratios These ratios indicate company’s profitability in relation to other companies, internal comparison with its previous year’s performance. They also indicate management effectiveness
Gross Profit ratio
This ratio represents cost of production.
It helps in understanding proportion of raw materials used and direct expenses incurred in overall production process.
This ration reflects income being generated which can be apportioned by promoters
This ratio also reflects efficiency of firm’s operations as well as how products are priced ADVANCED INFORMATION TECHNOLOGY TRAINING
339
ADVANCE MS-EXCEL
GPMR = Gross profit/ Net sales Gross Profit
= Net sales - COGS = 904 - 714 = 190
GPMR
= Gross Profit / Net sales = 190 / 904 = 0.21 = 21%
Implies 79% (100-21%) of sales contribute towards direct expenses and raw material.
Fig 4.2.3-13 Gross Profit Margin Ratio
Net Profit Ratio
It takes into account not only cost of production but also administrative expenses like staff salary, selling & distribution overheads.
It represents surplus of gross profit after meeting expenses.
Net profit is usually appropriated to meet tax liability, dividend payments and to retain part in business.
NPMR = Net profit (Profit after tax)/ Net sales = 52 / 904 = 5.7 %
This implies that every ` 100/- of sales, ` 5.7 /- earned as profit
Fig 4.2.3-14 Net Profit Margin Ratio
Return on Investment
This ratio indicates efficiency with which company used its capital (Equity as well as debt)
This ratio takes into consideration overall returns of the company assuming company has not taken any debt.
It gives overall returns including adjustments of earnings for financial leveraging.
It enables one to check whether return made on investment is better than other alternatives available.
RoI = EBIT x 100 / Capital Employed
EBIT = 143
Capital Employed = 566 ( ( 120 + 50 + 215 + 181 ) – ( 0 – 0) ) (Equity + Preference + Reserve & Surplus + Debt) – (Fictitious assets + Non-operating assets)
340
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
ROI = 143 / 566 x 100 = 25.26 %
The company has earned a profit of ` 25.26 paisa on every ` 100 reinvested as shown in Fig 4.2.3-15
Fig 4.2.3-15 Return on Investment
Valuation Ratios Earnings per share (EPS)
It represents total earnings of a company available for distribution among equity shareholders. Evaluates performance of company shares over a period of time
EPS = Net profit available for equity shareholders / No of Equity shares
EPS alone should not be basis of decision making with respect to purchase of any company share
Faulty reasons of High EPS
Less No of Equity shares
Investment in risky ventures
Price Earnings (PE) Multiple
It is the simplest method of comparing different stocks at a point of time to make investment decisions
As a layman, this is the price being paid for buying one rupee of earning of a company ex: If PE of Infosys share is Rs 9/- it means we are paying to the market a price of 9 for every Rs 1/earning of the company
PE Ratio = Market Price per share/ EPS
Price Earnings Growth (PEG) Multiple
An extension of PE which also takes into account growth rate of the company PEG Multiple = PE / Growth Company A
Company B
Market Price
200
200
EPS
10
20
ADVANCED INFORMATION TECHNOLOGY TRAINING
341
ADVANCE MS-EXCEL Growth rate
5%
2%
PE Ratio
20
( 200/10 )
10 ( 100 / 20 )
PEG Multiple
4
( 20 / 5 )
5 ( 10 / 2 )
Company A overvalued.
Company B overpriced wrt growth potential
With this we complete Ratio analysis. We shall now learn how to carry out Du Pont Analysis.
4.3
Du Pont Analysis
Du Pont Analysis helps to break down the Return on Equity (RoE).
4.3.1. What is ROE? Return on Equity is a financial ratio that shows you how well the management has created value for shareholders. ROE is made up of two numbers, net income and shareholders’ equity. ROE = Net Income/Shareholders Equity A high ROE generally means that the rate of return on shareholders’ equity is going up and that the company is doing a good job of growing profits without adding new equity into the business. A high and consistent ROE can signal that the company has a competitive advantage over its competitors.
4.3.2. Introducing the DuPont Analysis Du Pont Analysis dissects the ROE to tell you how the company is achieving its ROE. These are the three questions that the DuPont analysis can help you answer:
Is the company increasing margins?
Is the inventory turnover increasing?
Is leverage being used?
4.3.3. Three Step DuPont Analysis Model ROE = (Net Profit Margin x (Asset Turnover) x (Equity Multiplier)
Net profit margin shows operating efficiency
Asset turnover shows asset utilization efficiency
Equity multiplier shows financial leverage; where
Net Profit Margin = Net Income/Sales Asset Turnover = Sales/Total Assets Equity Multiplier = Total Assets/Shareholders Equity 342
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS When we multiply these three factors, Sales and Total Assets cancel each other out resulting in ROE as shown in Fig 4.3.3-1. ROE = (Net Income/Sales) x (Sales/Total Assets) x (Total Assets/Shareholders Equity)
Fig 4.3.3-1 Return on Equity
4.4. Leasing Leasing is a common method for financing property, facilities, and equipment. Leases are contracts between an asset’s owner (called the lessor) and the user (the lessee). A lease gives the lessee the right to use the asset in exchange for periodic payments to the lessor. For defining operating leases of equipment, the lessor is often a manufacturer that leases its own products to the lessee (sales-type leases). Sometimes the lessor is an independent leasing company that buys from the manufacturer and leases it to the lessee (direct leases). In this case, the lessor may borrow funds from creditors in order to buy the equipment from the manufacturer (leveraged leases). At other times, the owner of an asset sells it to another firm and immediately leases it back (sale and lease-back leases). This allows the original owner to raise cash for immediate needs and still retain the use of the asset while the lease is paid off. Lease terms vary. Operating leases are generally for shorter durations than the useful life of the asset leased and, for this reason, they are not fully amortized; the lessor does not recover the asset’s full cost. The lessor reacquires possession of the asset at the expiration of the operating lease and can lease it again for further use. Financial leases, on the other hand, are fully amortized. A lessee can cancel an operating lease before its expiration date. However, a lessee cannot cancel a financial lease and must make all payments or face bankruptcy. Leases also differ in requirements for the lessee to insure and maintain the leased asset and the right of the lessee to renew on the expiration of the lease. Leasing a car for a day or week during a vacation trip is an example of a short-term lease. Leasing trucks, factory machinery, computers, or airplanes for a number of years are examples of long-term financial leases that are involved in capital budgeting. Such leases are the most common method of financing equipment. ADVANCED INFORMATION TECHNOLOGY TRAINING
343
ADVANCE MS-EXCEL For the lessee, the choices are to buy or to lease. For the lessor, the problem is to identify the highest rental rate that would be acceptable to a lessee. The following case study is for a long-term financial lease of operating equipment from the standpoint of the lessee. It shows how to identify whether it is better for a company to lease or buy operating equipment. Note the treatment of depreciation, the firm’s cost of capital or discount rate, the lessor’s rental rate, and taxes. As the owner of the asset leased, the lessor gets a tax shield for the asset’s depreciation. The lessee can claim the lease payments as an operating expense. The benefits generated by the equipment and such expenses as maintenance, repair, and insurance are assumed to be the same regardless of whether the equipment is leased or purchased. Example 1: Suppose we want to buy a server and its cost is ` 1, 75,000/- and lease payments are ` 45,000/- with annual rate 8%
Fig 4.4-1 Leasing Example
Fig 4.4-2 Leasing Example – Formula mode 344
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS Example 2: A company is considering to acquire an additional machinery It has 2 options: Option 1:
To purchase machinery for Rs 2200000
Option 2: To lease the machinery for 3 years for ` 725000 as annual lease. The agreement also requires an additional payment Rs 600000 at the end of 3rd year Annual Operating Costs (excluding depreciation /lease rent of machinery) are estimated at ` 900000 with an additional cost ` 100000 for training cost at the beginning of the year. These costs are to be borne by lessee. The Company will borrow at 16% interest to finance the acquisition. The Machinery under review will be worth Rs 10 lacs at the end of 3 years. Repayments are to be made as follows:
Year end
Principal
Interest
1
5,00,000
3,52,000
2
8,50,000
2,72,000
3
8,50,000
1,36,000
The Company uses SLM to depreciate the assets & pays tax @ 50%. Which alternative is better? For solving this example we shall create two tables. One table will be used to evaluate NPV under the leasing option and second table will be used to evaluate NPV under the Purchase option. To recreate these tables use the formula as displayed in Table with Show formula mode enabled as shown in Fig 4.4.3.
Fig 4.4-3 Leasing Example 2: Evaluating Leasing Option ADVANCED INFORMATION TECHNOLOGY TRAINING
345
ADVANCE MS-EXCEL
Fig 4.4-4 Leasing Example 2: Evaluating Leasing Option (Formula-Mode)
Fig 4.4-5 Leasing Example 2: Evaluating Purchase Option
Fig 4.4-6 Leasing Example 2: Evaluating Purchase Option (Formula-Mode) 346
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS Under the leasing option we have made sure that tax has been considered and subtracted from the cash outflows. Then we apply the PV factor of 8% (16% x 50% tax rate) to the net cashflow. Under the purchase option we have subtracted tax component from the interest to ensure that we account for the tax benefit on the same. Also we subtract depreciation of 2,00,000/(Cost – Salvage value)/Life = [( 22,00,000 – 10,00,000 ) / 3] * 50% tax rate From above figures it is evident that NPV under the purchase option is lower than NPV under lease, thus purchasing the machinery is a better choice.
4.5. Financial Shenanigans Financial shenanigans are actions or omissions (tricks) intended to hide or distort the real financial performance or financial condition of an entity. They range from minor deceptions to more serious misapplications of accounting principles. Let us see one of the most famous (for all the wrong reasons) case of financial fraud and how it could have been detected by a simple analysis of Ratios and Charts
4.5.1. Enron case The table shows Enron sales figures for five years in a row. We shall first calculate the GP and NP ratio and then create a chart based on the same to compare their growth trend as shown given figures.
Fig 4.5.1.–1 Enron Annual Comparative
Fig 4.5.1–2 Enron Annual Comparative – Show formula mode ADVANCED INFORMATION TECHNOLOGY TRAINING
347
ADVANCE MS-EXCEL
Chart preparation Steps: (Note: Certain formatting options shown below are more or less same for all the charts) 1.
Select Range A2:F2
Fig 4.5.1–3 Select range 2.
Go to Insert Tab > Charts Section > Line Chart > 2D Line Chart > First option
Fig 4.5.1–4 Chart selection 3.
348
We get a chart which looks like the following image, click on this chart to enable Contextual Chart Tools. This will show three tabs: Design, Layout and Format tab
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
Fig 4.5.1–5 Chart image 4.
Goto Design Tab > Select Data button
Fig 4.5.1–6 Select Data Button 5.
We shall get the following window, click on Edit Button of Horizontal Axis labels
Fig 4.5.1–7 Click on Edit Button
ADVANCED INFORMATION TECHNOLOGY TRAINING
349
ADVANCE MS-EXCEL
Fig 4.5.1–8 Select Data Source 6.
We get “Axis Label Range” Selection Window. Select Range B1:F1. Click OK. X – Axis will now have years instead of numbers 1 to 5.
7.
Left click on Chart Title and Type “Enron Growth”. The type value appears in the formula bar. After typing, press Enter to save the chart title.
8.
Goto Layout tab > Data labels > Above
Fig 4.5.1–9 Go to Layout Tab 350
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
9.
Goto Layout tab > Gridlines > Primary horizontal gridlines > None
Fig 4.5.1–10 Select None 10.
Goto Layout tab > Legend > Show Legend at bottom. This will shift the chart index and place it below the chart.
Fig 4.5.1–11 Select Legend 11.
Left click on the plotted sales line such that the data points get selected.
ADVANCED INFORMATION TECHNOLOGY TRAINING
351
ADVANCE MS-EXCEL
Fig 4.5.1–12 Data Point
Data points 12.
Goto Layout Tab > Current Selection Section > Format Selection Button
Fig 4.5.1–13 Format Selection 13.
We get a Format Data Series window. Select Marker Options. Under Marker Type, Select Built-in option. Then Close the window.
Fig 4.5.1–14 Select Built-in 14. 352
On the design tab we have various chart styles. We can select any one from the given options or create a custom style. ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
Fig 4.5.1–15 Select Design tab 15.
As a result of the above settings we get the following chart. The following chart clearly shows the sudden increase in the revenues. The sudden increase shown in the chart itself is a sufficient sign to alert any person who is analyzing the revenues of the company.
Fig 4.5.1–16 Enron Growth Chart Chart preparation Steps: 1.
Select Range A4:F4, then keeping the Ctrl key pressed, select Range A6:F6 Thus we have selected two non-continuous ranges.
ADVANCED INFORMATION TECHNOLOGY TRAINING
353
ADVANCE MS-EXCEL
Fig 4.5.1–17 Select two non-continuous ranges 2.
Goto Insert Tab > Charts Section > Line Chart > 2D Line Chart > First option
Fig 4.5.1–18 Select 2D Line Chart 3.
354
As explained in the previous chart (a)
Enable Data labels.
(b)
Change Legend position
(c)
Add Data Markers.
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS 4.
As a result of the above formatting we shall get the following chart.
Fig 4.5.1–19 Profit Ratio trend From both the charts it is very evident with some basic charts, trend analysis and due diligence it was very much possible to understand that there was something really wrong with the company’s financial data. It wouldn’t be very difficult for a learned investor and a good auditor to recognize the anomalies in data.
4.6. Equity Research 4.6.1. What is Equity Research Equity research is a study of equities or stocks for the purpose of investments. Equities or common stock comprises a big chunk in any company’s capital and shareholders need to know whether to stay invested in the company or sale the shares and come out. As an individual, it is time consuming to do equity research – that is to study the company, its financial statements, products, management and take a decision about investment. Thus there are people working in research companies whose job is to do equity research and recommend companies for investment.
4.6.2. Valuation Methods Valuation models use time value of money principles or simpler market principles to value assets, stock and shares or the perceived value of future benefits. Valuation by different methods does not necessarily produce the same answers and the market employs a wide variety of methods. The purpose of this chapter is to set out some of the basic mathematics for valuation. Companies can be valued from several different angles: for example a liquidation value can be very different from a going concern. Alternatively, a stream of dividends is very different from cash flow although a long-term investor may view a company purely for its income potential. Similarly it depends on whether you are buying or selling. Since a flow of future benefits represents a forecast, the financial model has to ADVANCED INFORMATION TECHNOLOGY TRAINING
355
ADVANCE MS-EXCEL show all the inputs to enable risk analysis of the key variables. The valuation is very likely a range rather than a single point which should be compared by method and with other companies within a peer group. Methods fall into these main categories:
Asset and adjusted asset valuations;
Dividend models;
Market methods;
Free cash valuation.
4.6.3. Market methods Stock market and earnings methods using share prices, earnings per share and price / earnings per share (P/E) are traditional ways of forming benchmarks or comparisons. The mathematics are very simple and spreadsheets are not really required, although the benchmark is often needed for comparison and price ranges. Whilst the pricing reflects market sentiment about particular stocks which can rise on takeover speculation or fall during a crash, it does represent a fair price between a willing buyer and seller. The basic calculation is: Market value = no of shares * share price The model needs:
Earnings after tax and interest (NPAT)
Number of shares
Calculate earnings per share (EPS)
Price earnings per share (P/E) ratio
Current market price of share / EPS
The valuation can be derived from either:
P/E * earnings per share = share price
Share price * no of shares = market value
The net income and number of shares is on the Data sheet and from this the earnings per share can be calculated as approximately 0.07. The current share price is 5.0 so the price / earnings per share ratio is 71.43. The valuation is therefore P/E * Net earnings: 71.43 * 3.50 = 250. The data table in Figure 14.3 shows the sensitivity to the P/E ratio. This is a high figure and there are perhaps some problems relating to the variables used. The formula is: Value of equity = sustainable earnings * approx P/E ratio + value of non-operating assets 356
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
4.6.4. Dividend Growth model Suppose Big D, Inc. just paid a dividend of ` 30. It is expected to increase its dividend by 2% per year. If the market requires a return of 15% on assets of this risk, how much should the stock be selling for? D
(1 g)
D
0
1
R-g
R-g
P 0 P0 = D0(1+g)/(R-g) P0 = 30 * (1+.02) / (.15 - .02) = Rs 235. 2
Fig 4.6.4.-1 Dividend Growth Model Example Suppose ABC Ltd. is expected to pay a ` 120 dividend in one year. If the dividend is expected to grow at 5% per year and the required return is 20%, what is the price? P0 = D1/(R-g) P0 = 120 / (.2 - .05) = ` 800/-
ADVANCED INFORMATION TECHNOLOGY TRAINING
357
ADVANCE MS-EXCEL
Fig 4.6.4.– 2 Dividend Growth Model Example
4.6.5. Stock Price Sensitivity Analysis – growth percentage We shall perform a sensitivity analysis to see how the change in growth percentage affects Market price of shares. In this example we have Expected dividend as ` 2; Required Rate as 20% Using the formula learnt above we shall create a table by entering formula in Cell B6 After entering the formula double click on the fill handle in Cell B6 so the entire column will be filled with stock price for the respective growth percentage in the table.
Fig 4.6.5.– 1 Growth Percentage Chart preparation Steps: 1.
Select Range A5:B25.
2.
Goto Insert Tab > Charts Section > Scatter Chart > Select the chart as show below.
358
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
Fig 4.6.5.– 2 Select Scatter Chart 3.
Format the chart as explained in previous example.
Fig 4.6.5 – 3 Stock price sensitivity to dividend growth This chart clearly displays how the price increase with growth in dividend.
4.6.6. Stock Price Sensitivity Analysis – expected return We shall perform a sensitivity analysis to see how the change in expected return affects Market price of shares. In this example we have Expected dividend as ` 2; growth rate is 5% Using the formula learnt above we shall create a table by entering formula in Cell B6 ADVANCED INFORMATION TECHNOLOGY TRAINING
359
ADVANCE MS-EXCEL After entering the formula double click on the fill handle in Cell B6 so the entire column will be filled with stock price for the respective growth percentage in the table.
Fig 4.6.6.–1 Current Stock Price Chart preparation Steps: 1.
Select Range A5:B25.
2.
Goto Insert Tab > Charts Section > Scatter Chart > Select the chart as show below.
Fig 4.6.6.–2 Scatter Chart 3.
360
Select the numbers on X axis and double click on them. This will open a Format Axis window.
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
Fig 4.6.6 –3 Select Numbers on X-axis 4.
On the Format Axis window, change the following setting to 0.05 (5%) since our required rate starts at 5.5% we don’t want value 0 on X axis. After making this change close the window
Fig 4.6.6 –4 Format Axis 5.
Change the title of the chart to your preference.
6.
Depending on the formatting options used you shall get a chart similar to the following image.
ADVANCED INFORMATION TECHNOLOGY TRAINING
361
ADVANCE MS-EXCEL
Fig 4.6.6 –5 Stock price sensitivity to expected return rate This chart clearly depicts how the price falls with every increase in the Expected rate of return.
Summary Excel is an invaluable tool for data analysis. In this chapter, we learnt how to apply simple formula and functions that allow us to analyze financial data. We learnt to create and format charts. Charts are one of the most important visual analysis tools available in excel. We learnt how to use Du-pont analysis in excel by proper data structuring and simple functions. We also learnt decision making like whether it was feasible to Lease a machinery or should it be purchased. In addition, we also learnt how to use charts to analyze trends and recognize the possibility of a fraud.
References [1]
Excel 2010 Formulas; John Walkenbach; Wiley Publishing
[2]
Financial Shenanigans; Howard Shilit; Mc Graw Hill.
362
ADVANCED INFORMATION TECHNOLOGY TRAINING
CHAPTER
5
STATISTICAL TOOLS IN EXCEL
LEARNING OBJECTIVES To learn statistical features of excel To learn Testing of hypothesis To learn confidence interval To learn level of confidence and level of significance To learn ANOVA To learn Regression Analysis
5.0 Introduction This chapter focuses on the statistical features of Excel application. The primary goal of this chapter is not to impart knowledge of statistics as a subject, thus basic knowledge of statistics is presumed. A “Statistic” can be a numerical fact, like Google has a 5% return last month or a test average in a class was 79 points. Statistics as a discipline = It is an art and science of collecting, presenting and interpreting data. It’s an Art because the presentation of your analysis matters a lot. It’s a science because we must use the scientific methods of experiment and probability. Data means chunks of some values. It can be any value first name, last name, month names etc. Information is data represented in a useful way. Interpretation of data means that we make useful information from data, using statistics or any tool, so that we can take decisions. Since future is always uncertain we try to use statistics on the past data in an attempt to predict the future and take decisions important decisions.
5.1 Enable data analysis toolpak Go to File menu – Options – Add-ins Section as shown in Fig 5.1.1
ADVANCE MS-EXCEL
Fig. 5.1.1 Excel Option Enable Analysis Tool pack and click OK. A button called Data Analysis shall be added to Data tab – Analysis section as shown in Fig 5.1.2
Fig. 5.1.2 Add-Ins 364
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
5.2. Basic Statistical functions Arithmetic Mean: A typical value that represents all the data points. To get this value we just add up all the numbers and divide by the count. Let us take an example of marks of 40 students. We shall calculate the mean value of those marks using AVERAGE function as shown in Fig 5.1.3.
Fig. 5.1.3 Arithmetic Mean Median: When a data set has high fluctuations or extremes in its values we cannot take the arithmetic mean as a representative of the entire population. This is because the extreme values in the data set will drag the arithmetic mean too high or too low. Thus in such a scenario we use median which is the middle value in a given data set. Let us take an example of salaries. We have a data of salaries of 20 individuals, we shall calculate their median as well as mean as shown in Fig 5.1.4
Fig. 5.1.4 Arithmetic Median ADVANCED INFORMATION TECHNOLOGY TRAINING
365
ADVANCE MS-EXCEL Mode: Mode is the value with the highest recurrence in a given dataset as shown in Fig 5.1.5 Let us again take example of test scores and find Mode using MODE.SNGL function
Fig. 5.1.5 Mode
5.3. Testing of hypothesis Hypothesis is a statement about a population parameter subject to verification. Example: Suppose a report says that monthly salary of CAs in industry is ` 60,000/Now we may or may not agree with the above report. We may even try testing the authenticity of the claim by carrying out such an analysis in our region. This test that we conduct would be known as hypothesis testing.
5.3.1. Hypothesis, Tests and Errors Hypothesis testing is a statistical procedure that uses sample evidence and probability theory to determine whether a statement about the value of a population parameter:
Should be rejected Should NOT be rejected
After the testing we shall make a concluding statement about the population parameter based on sample evidence. Continuing the above example of CAs in industry, we actually try testing the report in our region and according to our test the average monthly salary turns out to be ` 63,500/-. We cannot immediately conclude that the original report was wrong or that our report is correct because our report is based on a sample that is different than the sample tested by the original report. Thus we need to first find out the difference between our result and the original result. The difference is ` 3,500 (` 63,500 – ` 60,000). This difference is known as Standard Error. We have to decide if this standard error is “statistically significant” or “statistically insignificant”. Thus what we have to follow a scientific procedure to reach a conclusion as to whether the result of our test is significant enough to override the original test. A hypothesis is a guess about the way the world works. It’s a tentative explanation of some process, whether 366
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS that process is natural or artificial. Before studying and measuring the individuals in a sample, a researcher formulates hypotheses that predict what the data should look like. Generally, one hypothesis predicts that the data won’t show anything new or interesting. Dubbed the null hypothesis (abbreviated H0), this hypothesis holds that if the data deviate from the norm in any way, that deviation is due strictly to chance. Another hypothesis, the alternative hypothesis (abbreviated H1), explains things differently. According to the alternative hypothesis, the data shows something important. After gathering the data, it’s up to the researcher to make a decision. The way the logic works, the decision centers around the null hypothesis. The researcher must decide to either reject the null hypothesis or not to reject the null hypothesis. Hypothesis testing is the process of formulating hypotheses, gathering data, and deciding whether to reject or not reject the null hypothesis. Regardless of the reject-don’t-reject decision, an error is possible. One type of error occurs when you believe that the data show something important and you reject H0, and in reality the data are due just to chance. This is called a Type I error. The other type of error occurs when you don’t reject H0 and the data are really due to something out of the ordinary. For one reason or another, you happened to miss it. This is called a Type II error as show in Fig 5.1.6
Fig. 5.1.6 Type II error
5.3.2. Case-Study Now that we have a basic understanding of hypothesis testing we shall take up the example of CAs in industry as shown in Fig 5.1.7
Fig. 5.1.7 Basic understanding of Hypothesis testing Before we reach to any conclusions we have to check whether difference of 3,500 is statistically significant. Thus we perform a hypothesis test and decide our Null and Alternate Hypothesis statement. We select a value of α that shall be acceptable to us.
ADVANCED INFORMATION TECHNOLOGY TRAINING
367
ADVANCE MS-EXCEL
Fig. 5.1.8 Hypothesis testing step-1 and step-2 Now we shall calculate X bar, Standard Error and Z value. We have the sample salaries in range A4:A39
Fig. 5.1.9 Hypothesis testing Step-3 We shall calculate the p-value and the critical value of the one talied test. This will help us to decide whether we have to reject or NOT reject to Null hypothesis.
Fig. 5.1.10 Hypothesis testing Step-4 Finally, we come to the conclusion that
Fig. 5.1.11 Hypothesis testing Step-5
368
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
5.4. Confidence Interval The Confidence Interval of a Mean is an interval in which the true population mean probably lies based upon a much smaller random sample taken from that population. A 95% Confidence Interval of a Mean is the interval that has a 95% chance of containing the true population mean. The width of a Confidence Interval is affected by the sample size. The larger the sample size, the more accurate and tighter is the estimate of the true population mean. The larger the sample size, the smaller will be the Confidence Interval. Samples taken must be random and also be representative of the population.
5.4.1 Level of Confidence and Significance Level of Significance: α ("alpha"), equals the maximum allowed percent of error. If the maximum allowed error is 5%, then α = 0.05. Level of Confidence: It is the desired degree of certainty. A 95% Confidence Level is the most common. A 95% Confidence Level would correspond to a 95% Confidence Interval of the Mean. This would state that the actual population mean has a 95% probability of lying within the calculated interval. A 95% Confidence Level corresponds to a 5% Level of Significance, α = 0.05. The Confidence Level therefore equals 1 – α Standard Error: It is an estimate of population Standard Deviation from data taken from a sample. If the population Standard Deviation (σ), is known, then the Sample Standard Error, Sxavg, can be calculated. If only the Sample Standard Deviation (s) , is known, then Sample Standard Error, Sxavg, can be estimated by substituting Sample Standard Deviation ( s ), for Population Standard Deviation ( σ ) , as follows: Sample Standard Error = Sxavg = σ / SQRT(n) = s / SQRT(n) σ = Population Standard deviation s = Sample standard deviation n = sample size
5.4.2 Region of Certainty vs Region of Uncertainty Region of Certainty is the area under the Normal curve that corresponds to the required Level of Confidence. If a 95% percent Level of Confidence is required, then the Region of Certainty will contain 95% of the area under the Normal curve. The outer boundaries of the Region of Certainty will be the outer boundaries of the Confidence Interval. Region of Uncertainty is the area under the Normal curve that is outside of the Region of Certainty. Half of the Region of Uncertainty will exist in the right outer tail of the Normal curve and the other half in the left outer tail.
5.4.3. Case-Study Calculate a Confidence Interval from a Random Sample of Test Scores Given the following set of 32 random test scores taken from a much larger population, calculate with 95% certainty an interval in which the population mean test score must fall. In other words, calculate the 95% Confidence Interval for the population test score mean. The random sample of 32 tests scores is shown next. ADVANCED INFORMATION TECHNOLOGY TRAINING
369
ADVANCE MS-EXCEL
Fig. 5.1.12 Random sample We shall use the following functions to get confidence interval boundaries: COUNT, AVERAGE, STDEV.S, SQRT, NORM.S.INV, CONFIDENCE
Fig. 5.1.13 Calculation
5.5. Analysis of Variance (ANOVA) 5.5.1. Introduction ANOVA, Analysis of Variance, is a test to determine if three or more different methods or treatments have the same effect on a population. For example, ANOVA testing might be used to determine if three different teaching 370
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS methods produce the same test scores with a group of students. The measured output must be some type of group average such as average test score per group or average sales per group. ANOVA testing might also be used to determine if different combinations of product pricing and promotion have different effects in different markets.
5.5.2. ANOVA Tests the Null Hypothesis The basic test of ANOVA is the Null Hypothesis that the different methods had no effect on the outcome that is being measured. Using the teaching method example, the Null Hypothesis in this case would be that the different teaching methods had no effect on the average test scores of student groups to which different treatments (teaching methods) were applied.
5.5.3. Single Factor ANOVA Single Factor ANOVA tests the effect of just one factor, in this case, the teaching method, on the measured outputs. The measured outputs are the mean test scores for the groups that had the different teaching methods applied to them. The Null Hypothesis for this one factor states that varying that factor has no effect on the outcome. We have units of products sold by three different groups of salesman throughout ten days. The observations of the groups are as follows as shown Fig 5.1.14
Fig. 5.1.14 One way ANOVA ADVANCED INFORMATION TECHNOLOGY TRAINING
371
ADVANCE MS-EXCEL
Go to Data tab and click on Data Analysis as shown in Fig 5.1.15
Fig. 5.1.15 Data Analysis
From the window that appears next click on Anova: Single factor
Fig. 5.1.16 Anova single factor
Select Input Range: =$C$3:$E$13 Grouped By: “Columns” Enable “Labels in first row” Set Alpha at 0.05 Select Output Range: =$G$1; Click OK.
Fig. 5.1.17 Click OK
372
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS Count of nos. in group Sum of observations
Average of observations Variance of observations
Average of observations
MS = SS/df F = MS between groups / MS within
Fig. 5.1.18 Output H0 = µa = µb = µc Ha = At least one inequality. Since p – value is greater than α we do not reject H0 Also, f value is far less than the f critical hence we are far away from the Rejection Region on f distribution diagram.
5.6
Prediction using Regression
Multiple Regression is a statistical tool used to create predictive models. The Regression Equation - the end result of the Regression – predicts the value of an output variable (the dependent variable) based upon the values of one or more input variables (the independent variables). If there are more than one independent variable, the Regression is classified as Multiple Regression. To begin the Regression procedure, you need completed sets of independent variables and their resulting outputs, the dependent variables. ADVANCED INFORMATION TECHNOLOGY TRAINING
373
ADVANCE MS-EXCEL To begin the Regression procedure, you need completed sets of independent variables and their resulting outputs, the dependent variables. Below is an example of the data needed to calculate a Regression equation as shown in Fig 5.1.19.
Fig. 5.1.19 Calculate Regression equation
5.6.1 Regression Equation Regression Analysis will be run on the above data. The output of the Regression Analysis below is called the Regression Equation: y = B0 + (B1 * x1) + (B2 * x2) + (B3 * x3) + (B4 * x4) B0, B1, B2, B3 and B4 are Coefficients of the Regression Equation. This Regression Equation allows you to predict a new output (the dependent variable y) based upon a new set of inputs (the independent variables x1, x2, x3, and x4).
5.6.2. Case-Study Below are the monthly rates of return of 4 stocks: (Google, Yahoo, MS, and Apple) and the Tech Index. Create a Regression Equation that will predict the Tech Index return for a given month if a different set of rates of return for each company's stock are input as shown in Fig 5.1.20.
Fig. 5.1.20 Case study The next step in the Regression process is to run a correlation analysis on all variables simultaneously. We only want to input variables in the regression equation that are good predictors of the independent variable. We 374
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS will examine the correlation between the dependent variable (the output that we are trying to predict) and each of the possible inputs (the independent variables). Correlation between two variables can take a value from anywhere between -1 and +1. The closer the correlation is to 0, the less correlated the two variables are and the less explaining power the independent variable has for the dependent variable. We want to remove any possible inputs from the regression equation if they have a low correlation with the output.
Go to Data tab and click on Data Analysis
Fig. 5.1.21 Go to Data Tab
From the window that appears next click on Correlation as shown in Fig 5.1.22
Fig. 5.1.22 Correlation
Select Input Range: =$B$13:$F$19 Grouped By: “Columns” Enable “Labels in first row” Select Output Range: =$A$22; Click OK.
Fig. 5.1.23 Click Ok ADVANCED INFORMATION TECHNOLOGY TRAINING
375
ADVANCE MS-EXCEL We shall get the following output. As marked in the output, Apple and Yahoo have low correlations with the Tech Index and therefore are not good predictors of the Tech Index. They should be removed. Also, if two of the independent variables above are highly correlated with each other, only one of them should be used in the Multiple Regression below. This is not the case here because none of the variables above have a high correlation with another variable. Using highly correlated variables as inputs to a Multiple Regression causes an error called Multicollinearity and should be avoided as shown in Fig 5.1.24
Fig. 5.1.24 Multiple Regression
After removing the two columns of Yahoo and Apple. We have the new data as follows.
Fig. 5.1.25 New data
Now we shall execute regression analysis. In the data analysis window select regression as shown in Fig 5.1.26
Fig. 5.1.26 Select Regression 376
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS
On the window that appears next configure the following
Input Y Range: $B$31:$B$37
Input X Range: $C$31:$D$37
Enable Labels.
Set Confidence Level at 95%
Set output range as $A$40
Enable Residuals
Click Ok
Fig. 5.1.27 Output Regression As a part of our regression analysis we get the following output.
Regression statistics and ANOVA
ADVANCED INFORMATION TECHNOLOGY TRAINING
377
ADVANCE MS-EXCEL
Fig. 5.1.28 Regression and ANOVA
Standard Errors and P-values
Fig. 5.1.29(A) Standard Errors and P-values
Fig. 5.1.29(B) Output
Residual Output
Fig. 5.1.30 Residual Output 378
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLIED FINANCIAL ANALYSIS Let’s take a look at the meaning of the output derived.
First and foremost we check the overall accuracy of the regression which is determined by R-square and adjusted R-square.
R-square is 90% which means that 90% of the variance of the output variable can be explained by the variance of input variable. Adjusted R-square is more conservative and more accurate.
Secondly, we check the probability that the regression output was not obtained by chance (co-incidence)
This can be determined by significance of F for the regression which in our case is 2.8%. Thus there is 2.8% chance that our regression output is mere co-incidence.
Third, we check the reliability of coefficients and y intercepts. This will be determined by the p-values. Smaller p-values means these values are not a result of co-incidence/chance.
Lastly, residuals are difference between actual tech index and predictive value of dependent variable. Thus the equation we get is: Tech Index = 0.251 + 0.393 * Google + 0.063 * MS
5.6.3. Using Regression equation to predict an output Predict the Tech Index if Google = 7 and MS = 4. Tech Index = (0.251) + (0.393)*(Google) + (0.063)*(MS) Tech Index predicted = (0.251) + (0.393)*(7) + (0.063)*(4) = 3.25
5.6.4. The Confidence Interval of the Output Variable The Confidence Interval was set at 95%. This is the default setting. It could have been set to any desired confidence level. The 95% Confidence Interval is interval in which the output variable, Tech Index, should fall with 95% certainty. The 95% Confidence Interval = Tech Index predicted +/- Z Score95% * (Standard Error) Z score Calculation Level of Confidence = 95% = 1 – α; Level of Significance = α = 0.05 Z Score 95% = Z Scoreα=0.05 = NORMSINV (0.975) = 1.96 The cell containing the Overall Standard Error for the Regression Equation = 1.33 The 95% Confidence Interval = 3.25 +/- (1.96) * (1.33) = 0.64 to 5.86 This means that there is a 95% chance the actual Tech Index return will fall within 0.64 and 5.86 for inputs Google = 7 and MS = 4.
ADVANCED INFORMATION TECHNOLOGY TRAINING
379
ADVANCE MS-EXCEL
Summary In this chapter we have glanced through some of the statistical features of excel. We have learn how to calculate and interpret ANOVA. We have learnt how to identify our Null and Alternate hypothesis. We have also learnt how to calculate basic statistical values like mean, median and mode. We have seen how to get a regression equation using regression analysis tools. Based on the derived equation we have learnt to predict an output. We have also learnt how to calculate the confidence interval of the output variable. Thus in this chapter we have touched upon various aspects of statistics as a subject and a few of its use cases in Excel.
References [1]
Statistical Analysis Microsoft Excel 2010 – Conard Carlberg
[2]
Excel Data Analysis Modeling and Simulation – Hector Guerrero
380
ADVANCED INFORMATION TECHNOLOGY TRAINING
CHAPTER
6
APPLICATION OF MS-EXCEL
LEARNING OBJECTIVES To know about the various tools available in excel regarding costing and finance. To know how to use these tools in practical situations.
6.1 Introduction Excel is a powerful tool available in the hands of users. Application of excel functions are unlimited. It depends on the imagination of the user only, how a function can be used in a particular situation. In this section we are going to discuss about some of the functions relating to accounting and finance. When excel was not there, still people used to analyze financial data using traditional tools with lot of limitation. After the availability of excel in the hands of the user, analysis of huge amount of data is possible at an absolutely great speed. In this section, we are going to discuss financial functions relating to depreciation calculation, marginal costing, cash budgeting, discounting, tax calculations, EMI calculations, capital budgeting, risk analysis and investment, financial planning, etc. In today’s era of technology, it is directly / indirectly compulsory for an accounting professional to learn these financial functions in excel to ensure his/her existence in this competitive world. Knowledge of these technological tools gives us an added advantage of handling huge amount of data at a great speed. So, let us start understanding one by one some of the useful functions in excel relating to accounting and finance.
6.2 Depreciation Accounting Depreciation stands for reduction in value of fixed assets. Value of fixed assets is generally reduced over the period of time due to any of the following reasons.
(a)
Wear & Tear
(b)
Change in taste of people
(c)
Change in technology.
ADVANCE MS-EXCEL Depreciation is considered as non cash expenditure and occupies a prominent place in Profit & Loss Account. If value of fixed asset is high, then depreciation may also be quite substantial figure. In excel, there are five different functions for calculation of depreciation. These are as under. Sr. No.
Function
Use
1
SLN
For calculation of depreciation as per Straight Line Method.
2
SYD
For calculation of depreciation as per Sum of Years’ Digit Method
3
DB
For calculation of depreciation as per Declining BalanceMethod.
4
DDB
For calculation of depreciation as per Double Declining Balance Method
5
VDB
For calculation of depreciation as per Variable Declining Balance Method
Table 6.2.1:Five different functions for calculation of depreciation 1. SLN Function: SLN function is used for calculation of depreciation figure as per Straight Line Method. In this method, the amount of depreciation remains constant over the period of time and it does not change every year. Following three inputs are required for calculation.
(a)
Cost – Cost incurred for acquiring fixed asset.
(b)
Salvage Value – The value which can be realized at the end of life of fixed asset by selling it.
(c)
Life – Total life of fixed assets in years as shown in Fig 6.2.1.
Fig.6.2.1: SLN function
2. SYD Function: SYD stands for Sum of Years’ Digits. Sum of the years' digits method of depreciation is one of the accelerated depreciation techniques which are based on the assumption that assets are generally more productive when they are new and their productivity decreases as they become old as shown in Fig 6.2.2. 382
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL Formula for calculation of depreciation under SYD is as under
Remaining Useful Life Sum of Years’ Digits
Depreciation
= Depreciable Base x
Depreciable Base
= Cost less Salvage Value
Remaining Useful Life
= Useful life remaining in the beginning of each year for which depreciation is to be calculated.
Sum of Years’ Digits
= Total of digits of years.
E.g. if total life of asset is 10 years, the sum of years digit shall be 10+9+8+7+6+5+4+3+2+1 = 55.
Fig.6.2.2: SYD function
3. DB Function: DB stands for declining balance. This method uses a fixed rate to calculate depreciation. Rate is calculated using the formula as under. Rate
=
1 – ((Salvage Value / Cost) ^ (1 / Life))
Depreciation
=
(Cost – Previous Depreciation) x rate
Amount of depreciation will keep on decreasing every year. The total amount of depreciation amount for all the years shall be equal to the cost less salvage value as shown in Fig 6.2.3.
ADVANCED INFORMATION TECHNOLOGY TRAINING
383
ADVANCE MS-EXCEL
Fig.6.2.3: DB function
4. DDB Function: When calculating the depreciation of an asset, it is common to use an accelerated depreciation calculation, in which the calculated value of an asset is reduced by a larger amount during the first period of its lifetime, and smaller amounts during subsequent periods. One of the most popular accelerated depreciation methods is the Double Declining-Balance Method, in which the straight-line depreciation rate is doubled. The Excel DDB function uses the following equation to calculate the depreciation
Fig.6.2.4: DDB function Following variables shall be used in the calculation of depreciation using DDB function. Cost – Initial cost of the asset 384
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL Salvage – Value of asset at the end of the life of asset Life – The total number of periods over which the asset is being depreciated. It is sometimes called as the useful life of the asset. Period – The period for which you want to calculate depreciation. Period must use the same units as life. E.g. Depreciation for 2nd Year, 3rd Year, etc. Factor – The rate at which balance declines. If omitted, it is assumed as 2.
5. VDB Function: VDB stands for variable declining balance. The VDB function uses the DDB (Double Declining Balance) method by default. The VDB function performs the same calculations as the DDB function. However, it switches to Straight Line calculation to make sure you reach the salvage value. It only switches to Straight Line calculation when Depreciation Value as per Straight Line Method is higher than Depreciation Value as per DDB method. There are two additional arguments in VDB function. Start_period – It is starting period for which you want to calculate depreciation. End_period – It is the ending period for which you want to calculate depreciation. VDB function is much more versatile than the DDB function. It can calculate the depreciation value of multiple periods as shown in Fig 6.2.5.
Fig 6.2.5: VDB function Example : Let us try to find out the depreciation calculation using all the five methods discussed above.
Cost
:
1,00,000
Salvage :
10,000
Life
:
10 ADVANCED INFORMATION TECHNOLOGY TRAINING
385
ADVANCE MS-EXCEL Period
SLN
SYD
DB
DDB
VDB
1
9,000.00
16,363.64
20,600.00
20,000.00
20,000.00
2
9,000.00
14,727.27
16,356.40
16,000.00
16,000.00
3
9,000.00
13,090.91
12,986.98
12,800.00
12,800.00
4
9,000.00
11,454.55
10,311.66
10,240.00
10,240.00
5
9,000.00
9,818.18
8,187.46
8,192.00
8,192.00
6
9,000.00
8,181.82
6,500.84
6,553.60
6,553.60
7
9,000.00
6,545.45
5,161.67
5,242.88
5,242.88
8
9,000.00
4,909.09
4,098.37
4,194.30
4,194.30
9
9,000.00
3,272.73
3,254.10
3,355.44
3,388.61
10
9,000.00
1,636.36
2,583.76
2,684.35
3,388.61
Total
90,000.00
90,000.00
90,041.25
89,262.58
90,000.00
6.3 MARGINAL COSTING In economics and finance, marginal cost stands for change in the total cost that arises when the quantity produced has an increment by unit. That is, it is the cost of producing one more unit of a good.It is computed in situations where the breakeven point has been reached: the fixed costs have already been absorbed by the already produced items and only the direct (variable) costs have to be accounted for. Marginal costs are variable costs consisting of labor and material costs, plus an estimated portion of fixed costs (such as administration overheads and selling expenses). In companies where average costs are fairly constant, marginal cost is usually equal to average cost. However, in industries that require heavy capital investment (automobile plants, airlines, mines) and have high average costs, it is comparatively very low. The concept of marginal cost is critically important in resource allocation because, for optimum results, management must concentrate its resources where the excess of marginal revenue over the marginal cost is highest. It is also called choice cost, differential cost, or incremental cost. Marginal costing is the system of calculating marginal costs for the purpose of financial and business decisions. Various concepts and tools are used for calculating marginal costs for the purpose of business decision making. Marginal costing mainly uses terms as under. Understanding of these terms is necessary before we proceed to discuss marginal costing in Excel.
Marginal Costing Equations: Following equations are used in Marginal Costing. (a)
Profit
= Sales – Total Cost
(b)
Total Cost
= Fixed Cost + Variable Cost
(c)
Contribution = Sales – Variable Cost
386
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL The whole idea of marginal costing revolves around a simple equation as under. Fixed Cost + Profit = Sales – Variable Cost
(a)
Fixed Costs: As the name suggest, these cost remain fixed irrespective of level of production. Fixed cost need to be incurred even if there is no production. Examples of fixed cost can be Salary of administrative staff, office rent, audit fees, etc.
Fixed Cost = Sales – Variable Cost – Profit Fixed Cost = (Sales x PV Ratio) – Profit
(b)
Variable Costs: As the name suggest, these cost vary according the volume of production. Total variable cost changes after every unit of production. But variable cost per unit remain the same. All direct costs are variable costs. E.g. raw material cost, commission to salesman, etc. are variable cost.
Variable Cost = Sales – Fixed Cost – Profit Variable Cost = Sales x Variable Cost Ratio (Variable Cost Ratio = 1 – PV Ratio)
(c)
Sales: This is the amount generated from selling of products. Total sales can be obtained by multiplying selling price per unit with number of products sold.
(d) Contribution: It is the difference between sales and variable cost. As the sales and variable cost can be calculated for each unit, it also possible to calculate contribution per unit using the simple formula as under. Contribution per unit =
Selling Price per Unit - Variable Cost per Unit Or
Contribution per unit =
Total Sales Value – Total Variable Cost No. of units sold
(e)
PV Ratio: Profit Volume Ratio expresses mathematical relationship between two variables, i.e. Profit and Volume of sales. It can be calculated by using any formula as stated below.
PV Ratio
= (Contribution / Sales) x 100
PV Ratio
= [(Sales – Variable Cost) / Sales] x 100
PV Ratio
= 1 – Variable Cost Ratio
PV Ratio
= (Change in Profit / Change in Sales) x 100
(f)
BEP: Break Even Point is the point of no profit or no loss. It may be expressed in terms of sales value or sales unit. It can be calculated as under.
BEP (Value) =
Fixed Cost PV Ratio
BEP (Units) =
Fixed Cost Contribution per Unit
ADVANCED INFORMATION TECHNOLOGY TRAINING
387
ADVANCE MS-EXCEL
(g)
Margin of Safety: It is the value of sales above the BEP point. It denotes how much safe we are about not incurring losses. If BEP sales is ` 100 and total sales is ` 140, then margin of safety is calculated as 40, i.e. 140 -100 using the formula as under. Margin of Safety = Total Sales – BEP Sales
BEP Calculation Excel can be conveniently used for preparation of chart showing Break Even Point. BEP level can also be calculated without using excel. But it is very easy to change the variables like selling price, variable cost and fixed cost to see the change in BEP level. Problem 1: Prepare a chart showing BEP when Selling Price is of a ` 600, Variable Cost is ` 250 and Fixed Cost is ` 4200 as shown in Fig 6.3.1(A).
Fig 6.3.1(A): BEP Calculation 388
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL Pricing Decisions & Discounts:
Excel can also be used for taking decision on product pricing. When large size data is to be handled excel can be really useful in such cases. Problem 2:
SRT Enterprises is into business of selling cricket bats. They have to take a decision about price of the product. Before the price is decided, marketing department is being consulted about the sales in quantity that can be achieved in the first year. SRT Enterprises wishes to achieve BEP in the first year itself. Consider following data. Variable Cost = ` 250, Fixed Cost = 10.00 Lacs. Sales Price Range = ` 300 to ` 1,000 A chart can be prepared as under to help in decision making as shown in Fig 6.3.2(B).
Fig 6.3.2(B): BEP Calculation As it is clear from the above table, if selling price is set at ` 1,000, BEP shall be achieved by selling 1,333 units while it will take 20,000 units to achieve BEP is product is priced at ` 300. ADVANCED INFORMATION TECHNOLOGY TRAINING
389
ADVANCE MS-EXCEL
Calculation of Marginal Revenue If we wish to calculate marginal revenue that would be generated at different sales levels with different selling prices, following formula can be used. Change in Sales Change in Quantities
This problem can be solved very easily in excel as given the picture below.
Fig 6.3.3: Calculation of Marginal Revenue Excel can be used in variety of ways for marginal costing and for taking business decisions using marginal costing. Above examples are just illustrative and not exhaustive.
6.4 Cash Budgeting Budget stands for planning for future. Cash budget is prepared for planning for future as far as movement of cash is concerned. Movement of cash includes inflow and outflow of cash. Normally bank transactions are also considered in cash budget. Cash budget is useful in maintaining the smooth flow of cash in business as well as to ensure liquidity during the budget period. Many financial and business decisions are taken on the basis of cash budget, e.g. how much credit to be given to customer, how much funding to be taken from outside sources, etc. The inputs to the cash budget come from several other budgets. The results of the cash budget are used in the financing budget, which itemizes investments, debt, and both interest income and interest expense. The cash 390
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL budget is comprised of two main areas, which are Sources of Cash and Uses of Cash. The Sources of Cash section contains the beginning cash balance, as well as cash receipts from cash sales, accounts receivable collections, and the sale of assets. The Uses of Cash section contains all planned cash expenditures, which comes from the Direct Materials Budget, Direct Labor Budget, Manufacturing Overhead Budget, and Selling and Administrative Expense budget. It may also contain line items for fixed asset purchases and dividends to shareholders. If there are any unusually large cash balances indicated in the cash budget, these balances are dealt with in the financing budget, where suitable investments are indicated for them. Similarly, if there are any negative balances in the cash budget, the financing budget indicates the timing and amount of any debt or equity needed to offset these balances. Cash may be prepared for any period ranging from a daily to yearly. A sample cash budget in excel can be prepared as shown in Fig 6.3.4.
Fig 6.3.4: Sample Cash Budget Requirements for preparation of cash budget in Excel:
Knowledge of accounting
Knowledge of formatting an excel sheet
Knowledge of cell linking
Knowledge of basic formulae ADVANCED INFORMATION TECHNOLOGY TRAINING
391
ADVANCE MS-EXCEL Figure under each head of inflow and outflow may be brought from a separate sheet, e.g. Cash Sales may be brought from Sales Budget Sheet, Loan Repayment figures may be brought from separate loan repayment schedule. These figures should be linked with the cells in other sheet so as to update the data on real time basis, automatically.
Budget & Actual Purpose of any budget is not fulfilled till the time budget figures are compared with actuals and a suitable corrective action is taken, if required. A budget with actual figures along with variance can be prepared as shown in Fig 6.3.5.
Fig 6.3.5: A Budget with actual figures
Budget Template Excel provides a readymade template for preparation of personal monthly budget, which may be used as it or along with modifications as required. Follow the steps as given under. (a) 392
Open a new or any existing excel file. ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL (b)
Right click on any sheet tab.
(c)
Click on “Insert”.
(d)
Click on “Spreadsheet Solutions” tab.
(e)
Double click on Personal Monthly Budget to open it.
Fig 6.3.6: Budget Template (f)
Following format of budget shall get opened on your screen.
Fig 6.3.6: Format of Budget
ADVANCED INFORMATION TECHNOLOGY TRAINING
393
ADVANCE MS-EXCEL
6.5 Discounting Discounting is the process of determining the present value of a payment or a stream of payments that is to be received in the future. Given the time value of money, a rupee is worth more today than it would be worth tomorrow given its capacity to earn interest. Discounting is the method used to figure out how much these future payments are worth today. Discounting is one of the core principals of finance and is the primary factor used in pricing a stream of cash flows, such as those found in a traditional bond or annuity. For example, the succession of coupon payments found in a regular bond is discounted by a certain interest rate and summed together with the discounted par value to determine the bond's current value.
Discounting Factor A discount factor can be thought of as a conversion factor for time value of money calculations. Time value of money calculations are based on the principle that funds placed in a secure investment earn interest over time. In the past, it was common to refer to a discount factor table to look up the number needed to perform a time value of money conversion. With the use of calculators and spreadsheets, the table lookup technique is practically obsolete.
Using Excel for calculating Discounting Factor Discounting factor can be calculated by using a simple formula as under Discounting Factor = 1 / (1+r) ^ n Where r = rate of interest and n = the year number for which discounting factor is to be calculated. Let us consider a case where we wish to calculate the discounting factor for 10 years at interest rate of 11%. This can be done very easily in excel as shown in Fig 6.5.1.
Fig 6.5.1: Calculating Discounting Factor
394
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL These discounting factors can be multiplied with cash flow values to get the present value of future cash flows. Basically, discounting factors are used to calculate present value of future cash flows. One can get this even without calculated discounting factors. Many excel functions like PV, FV, IRR can be used to calculate the discounted value of cash flow without using the above mentioned formula. These functions are discussed later in other topics.
6.6 Tax Computations Using Excel Excel can be conveniently used for preparation of tax computations. Let us prepare a computation sheet using some of the excel features.
1.
File Creation
Create a new excel file and save it at desired location.
2.
Sheet Formatting
Format the sheet as per requirement. Type the headings are required. Prepare the computation of income as per the required format without using any special excel function or feature. All types of controls and validation can be placed later on. A sample computation sheet is given for your reference as shown in Fig 6.6.1.
ADVANCED INFORMATION TECHNOLOGY TRAINING
395
ADVANCE MS-EXCEL Assessee PAN Date of Birth
: Shashank Prakash Deshpande : AFIPD0679G : 17-03-1978
Assessment Year Previous Year Status
: 2014-15 : 2013-14 : Individual
Computation of Income Income From Profession : Profit As Per Profit & Loss Account Less : Interest on Savings Account Less : Other Interest Income Less : Interest on Fixed Deposits Less : Share of Profit in Partnership Firm Total Income From House Property : Annual Value (Self Occupied) Less :Deduction for Interest on Housing Loan (50% of 1,24,475) Income From Other Sources : Interest on Savings Bank Account Interest on Fixed Deposits Interest other Gross Total Income Less : Deductions Under Chapter VI-A Principal Repayment on Housing Loan (50% of 140348) Kotak Life Insurance ELSS Mutual Fund Total Investment u/s 80C Total Deductions
7,55,542 3,994 7,496 24,213 68,055 6,51,784
62,238
3,994 24,213 7,496
70,174 4,437 60,000 1,34,611 1,34,611
Total Income Less : Short Term Capital Gain Taxable Income Total income rounded off under section 288A Tax on Above Income Short Term Capital Gain Tax Total Tax Add: Eduction Cess @ 3% Total Tax Payable Add : Interest Total Tax + Interest Payable Less : Tax Deducted at Source Refund Due
6,51,784
(62,238)
35,703 6,25,250
1,00,000 5,25,250 5,25,250 5,25,250 35,050 35,050 1,052 36,102 36,102 54,117 (18,016)
Shashank Prakash Deshpande (Assessee)
Fig 6.6.1: Tax Computation using Excel
396
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
3.
Sheet & Cell Protection
Once the basic format is ready, we can move towards locking the sheet / cells for editing. This will prevent the user from changing the sheet formatting, titles and thus disturbing the computation sheet. This can be done as shown in Fig 6.6.2 and Fig 6.6.3. (a)
By default all the cells in any excel sheet are locked. We must unlock the cells which we wish to keep open for users for data input. Select such cells and…. Right Click > Format Cells > Protection > Uncheck the “Locked” check box.
Fig 6.6.2: Unlock cell Once this is done, the selected cells shall not be locked and other remaining cells shall be locked. (b)
Go to Review Tab> Protect Sheet. Type the password. Password is optional.
Fig 6.6.3: Password to Protect Sheet This will ensure that the sheet is protected from all unwanted and unauthorized changes by users. The users shall be allowed to type or edit the text in selected fields only.
1. Setting Input Validations (a)
Date – Only date shall be entered in the filed for date of birth. This can be done by selecting the validation criteria as Date. ADVANCED INFORMATION TECHNOLOGY TRAINING
397
ADVANCE MS-EXCEL
(b)
PAN – PAN must have 10 characters only. Further, the first five characters shall be alphabets, next four characters shall be numbers and the last, i.e. 10th character shall be an alphabet only. For setting this type of validation, PAN has to be written in 10 different cells with 10 different validations.
(c)
Value – Fields meant for typing figures, e.g. income shall allow only figures and not text. This can be done by selecting the validation criteria as “Whole number”.
(d)
Status – Status can be selected from the list of drop down option as Individual, Firm, Company, Society, etc. This can be done by using the validation criteria as “List”. This To set validation rules, go to Data > Validation. Any validation rule can be selected and set as per requirement as shown in Fig 6.6.4.
Fig 6.6.4: Data Validation
2. Tax Calculations Method of tax calculations shall change according to status of assess, date of birth, etc. Let us consider a practical case as under. Income
:
` 11,62,500
Status
:
Individual (Age Below 60 Years)
Calculate the tax payable for AY 14-15 This can be easily done in excel using IF function as shown in Fig 6.6.5.
398
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Fig 6.6.5: Tax Calculation Explanation to formula used. 1. For 10% slab – Check if the income is greater than ` 5.00 lacs, if yes, the tax shall be ` 30,000. If no, then check if the income is greater than ` 2.00 lacs, if yes then tax shall be 10% of excess of income over ` 2.00 lacs). If income is even less than ` 2.00 lacs, the tax shall be zero. 2. For 20% slab – Check if income is greater than ` 10.00 lacs, if yes, then the tax shall be ` 1.00 lacs. If no, then check whether income is greater than ` 5.00 lacs, if yes, then tax shall be 20% of excess of income above ` 5.00 lacs. If income is not greater than ` 5.00 lacs, then tax shall be zero. 3. For 30% slab – Check if income is greater than ` 10.00 lacs, if No, tax shall be zero. If yes, tax shall be 30% of income above ` 10.00 lacs.
6.7 EMI Calculations Using Excel EMI stands for equated monthly installment. This is very often needed in case of taking any type of finance decision. May it be lender or borrower, both the parties are always interested in knowing the amount of monthly installment that shall be payable. Installments are equated over the period of time for the sake of simplicity. There are certain points which need to be understood about EMI.
Every installment amount shall include principal amount as well as interest amount.
Interest amount shall be highest in the first EMI and lowest in the last EMI. Interest portion shall reduce gradually in every next EMI.
Principal amount shall be lowest in the first EMI and highest in the last EMI. Principal portion shall increase gradually in every next EMI. ADVANCED INFORMATION TECHNOLOGY TRAINING
399
ADVANCE MS-EXCEL The biggest challenge in the above calculation is to how to change the proportion of principal and interest in every next EMI. This can be easily done using excel. Case Study: Mr. A want to avail a loan of ` 1.00 lacs. Repayment period is three years and rate of interest is 12% p.a. Please let him know what shall be the EMI. Solution: Equated Monthly Installment can be very easily calculated using PMT function as shown in Fig 6.7.1. (a)
Type the data in excel as given under.
Fig 6.7.1: Using PMT function (b)
Select the cell where you want the result and click on the function button as shown in Fig 6.7.2
Fig 6.7.2: Select the cell Following screen shall appear after clicking on “fx” button as shown in Fig 6.7.3.
400
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Fig 6.7.3: Screen of Financial function Various types of functions are available in excel. Here the relevant function is “PMT” which stands for payment. This function is a part of Financial Functions in excel. Select the category as “Financial” and select “PMT” function. After selecting “PMT” function, following screen shall appear as shown in Fig 6.7.4.
Fig 6.7.4: Selecting PMT function
Rate – It is the rate of interest, to be divided by 12 for getting monthly rate of interest.
Nper – It is total number of periods, i.e. 60 months in this case.
PV – It is present value of cash flows, i.e. loan amount as on today. ADVANCED INFORMATION TECHNOLOGY TRAINING
401
ADVANCE MS-EXCEL All the above values can be typed or liked with cells in excel sheet for real time updation. As soon as all the values are entered / linked correctly, formula result is displayed at the bottom as ` 2,224.44. It is displayed as a negative figure just because excel considers all outflows are considered as negative figure. After clicking on OK button, the result shall be generated in the desired cell as shown in Fig 6.7.5.
Fig 6.7.5: Result of PMT function PPMT Function This function is used to calculate the principal portion in every installment. This function requires one additional input, i.e. the installment number. The principal amount shall increase after every installment. Hence, principal amount shall be different in every EMI. Continuing with the above example, the following figure shows calculation of principal and interest component in each EMI. Installment number is denoted by “Per” in excel. For the calculation of interest component in each EMI, excel has IPMT function. Both the functions are used in the following figure.
402
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Fig 6.7.6: PPMT function Loan Amortization Sheet
Excel provides a readymade solution for the EMI calculation. This can be simply done by following steps as shown in Fig 6.6.7. (a)
Open any excel file
(b)
Right click on sheet tab.
(c)
Select “Insert” option.
(d)
Go to “Spreadsheet Solutions” tab
(e)
Select “Loan Amortization” and click OK button.
ADVANCED INFORMATION TECHNOLOGY TRAINING
403
ADVANCE MS-EXCEL
Fig 6.7.7: Loan Amortization Sheet template (f)
Enter all the details like Loan Amount, Annual interest rate, Loan period in years, Number of payment per year, Start date of loan, etc. All the EMI calculations shall be displayed as shown in Fig 6.7.8.
Fig 6.7.8: Loan Amortization Sheet template 404
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
6.8 Sampling Sampling is the process of selecting units (e.g., people, organizations) from a population of interest so that by studying the sample we may fairly generalize our results back to the population from which they were chosen. Two words often used in sampling are sample and population. Sample means the units or items selected for study or consideration and population means the total set of data used for selection of samples. Sampling is a process used in statistical analysis in which a predetermined number of observations will be taken from a larger population. The methodology used to sample from a larger population will depend on the type of analysis being performed, but will include simple random sampling, systematic sampling and observational sampling. The basic expectation from sampling is that the sample should be a representation of the general population. When taking a sample from a larger population, it is important to consider how the sample will be drawn. To get a representative sample, the sample must be drawn randomly and encompass the entire population. For example, a lottery system can be used to determine the average age of students in a college by sampling 20% of the students, considering an equal number of students from each type of course.
Sampling Methods Following are some of the sampling methods. 1. Simple random sampling: In this case each individual is chosen entirely by chance and each member of the population has an equal chance, or probability, of being selected. One way of obtaining a random sample is to give each individual in a population a number, and then use a table of random numbers to decide which individuals to include. 2. Systematic sampling: Individuals are selected at regular intervals from a list of the whole population. The intervals are chosen to ensure an adequate sample size. For example, every 10th member of the population is included. This is often convenient and easy to use, although it may also lead to bias. 3. Stratified sampling: In this method, the population is first divided into sub-groups (or strata) who all share a similar characteristic. It is used when we might reasonably expect the measurement of interest to vary between the different sub-groups. Gender or smoking habits would be examples of strata. The study sample is then obtained by taking samples from each stratum.
In a stratified sample, the probability of an individual being included varies according to known characteristics, such as gender, and the aim is to ensure that all sub-groups of the population that might be of relevance to the study are adequately represented. The fact that the sample was stratified should be taken into account at the analysis stage. 4. Clustered sampling: In a clustered sample, sub-groups of the population are used as the sampling unit, rather than individuals. The population is divided into sub-groups, known as clusters, and a selection of these are randomly selected to be included in the study. All members of the cluster are then included in the study. Clustering should be taken into account in the analysis.
ADVANCED INFORMATION TECHNOLOGY TRAINING
405
ADVANCE MS-EXCEL
The General Household survey, which is undertaken annually in England, is a good example of a cluster sample. All members of the selected households/ clusters are included in the survey. 5. Quota sampling: This method of sampling is often used by market researchers. Interviewers are given a quota of subjects of a specified type to attempt to recruit. For example, an interviewer might be told to go out and select 20 adult men and 20 adult women, 10 teenage girls and 10 teenage boys so that they could interview them about their television viewing. There are several flaws with this method, but most importantly it is not truly random. 6. Convenience sampling: Convenience sampling is perhaps the easiest method of sampling, because participants are selected in the most convenient way, and are often allowed to chose or volunteer to take part. Good results can be obtained, but the data set may be seriously biased, because those who volunteer to take part may be different from those who choose not to. 7. Snowball sampling: This method is commonly used in social sciences when investigating hard to reach groups. Existing subjects are asked to nominate further subjects known to them, so the sample increases in size like a rolling snowball. For example, when carrying out a survey of risk behavior amongst intravenous drug users, participants may be asked to nominate other users to be interviewed.
Simple Random Sampling in Excel Consider a small case of analysis of customer feedback about a product. Let us assume that we have a population of 1000 customer feedback forms. We need to analyze the feedback pattern of 5% customer, .i.e. 50 customers. This can be done easily by following steps as under shown in Fig 6.8.1.
(a)
Write Column heading in Cell A1 as Customer IDs and write customer codes / IDs in Cell A2, A3,A4, and so on.
(b)
Go the cell B1 and write the column heading as Random Numbers.
(c)
Go to cell B2 and type “Rand()” and press ENTER. This is a function for generating random numbers in any particular cell. After pressing ENTER, a random number shall be generated in cell B2.
(d)
Copy Cell B2 and paste it in the Cells B3, B4, B5, etc. Now in-front of every customer ID, there is a random number.
(e)
Sort both columns according to random numbers
406
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Fig 6.8.1: Simple Random Sampling (f)
Select the first 50 customers. Now these 50 customers are the randomly selected customers and represent the complete data.
Using Sampling Feature Excel has got a built in feature for sampling of data. This can be used as under. (a)
Type the data regarding roll number of students in Cell A2, A3, A4, and so on.
(b)
To get a sample of five students, go to Data > Data Analysis
Fig 6.8.2: Sampling Feature (c)
Select “Sampling” from the list and click OK.
ADVANCED INFORMATION TECHNOLOGY TRAINING
407
ADVANCE MS-EXCEL
Fig 6.8.3: Select Sampling (d)
Following screen shall appear.
Fig 6.8.4: Sampling There are three options for user to set.
Input Range – Specify the population range here.
Sampling Method – Select the method from two options. If periodic is selected, period, i.e. interval needs to be specified. If random is selected, number of samples required from the population has to be specified.
Output options – Specify the location where you want the sampled data. It may the specific location in the same sheet, or some other sheet or in a new file also.
(e) Click OK to get the result. Following type of screen shall be generated. In this case we have considered a population of twenty students and we are obtaining samples of five students. 408
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Fig 6.8.5: Obtained Sampling
6.9
Summary
Summary reports are useful for quick reading and easy understanding, particularly for top management. When excel is used for preparation of reports in similar formats, it can be used for consolidation of reports into a master report or a summary report. Additional operations like average, count, sum can be done while preparing summary reports. To summarize and report results from data on separate worksheets, you can consolidate the data from each separate worksheet into one worksheet (or master worksheet). The worksheets you consolidate can be in the same workbook as the master worksheet or in other workbooks. When you consolidate data in one worksheet, you can more easily update and aggregate it on a regular or ad hoc basis. For example, if you have a worksheet of expense figures for each of your regional offices, you might use data consolidation to roll up these figures into a corporate expense worksheet. This master worksheet might contain sales totals and averages, current inventory levels, and highest selling products for the entire enterprise. Example:
Let us consider a case where the data about debtors for two months is stored in two different sheets. We wish to consolidate the data in third sheet. Solution:
Let us assume that names of debtors are stored in Cell A2, A3, A4, and so on and monthly purchases by them are recorded in Cells B2, B3, B4, and so on. Data for the month of April is stored in Sheet1 and data for May is stored in Sheet2. Let us consolidate the data in Sheet3.
(a)
Create a new sheet and rename it as Summary. ADVANCED INFORMATION TECHNOLOGY TRAINING
409
ADVANCE MS-EXCEL
(b)
Go to Data > Consolidate (Under Data Tools Group)
(c)
Following type of screen shall appear as shown in Fig 6.9.1.
Fig 6.9.1: Consolidate Data (d)
Select the required function from the drop down menu. Here we have selected Sum.
(e)
Select the table array (A2:B11) from Sheet1 in Reference and click on Add button.
(f)
Now, select the reference (A2:B11) from Sheet2 in Reference and click on Add button.
(g)
As we have stored the names of customer in A column, check the check box “Left column”
(h)
Click on OK button. The result shall be generated on “Summary” sheet.
(i)
If the check “Create links to source data” is clicked, summary report shall be linked with source data on real time basis. Updations in Sheet1 or Sheet2 shall be updated in Summary sheet also.
Fig 6.9.2: Create links to source data 410
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Data can be summaries by using the Consolidate command (Data tab, Data Tools group). Other way of data consolidation is using formulae like COUNTIF, SUMIF, etc. or a PivotTable report also.
6.10 Capital Budgeting It is a process in which a business determines whether projects such as building a new plant or investing in a long-term venture are worth pursuing. Oftentimes, a prospective project's lifetime cash inflows and outflows are assessed in order to determine whether the returns generated meet a sufficient target benchmark. Ideally, businesses should pursue all projects and opportunities that enhance shareholder value. However, because the amount of capital available at any given time for new projects is limited, management needs to use capital budgeting techniques to determine which projects will yield the most return over an applicable period of time. Popular methods of capital budgeting include net present value (NPV), internal rate of return (IRR), discounted cash flow (DCF) and payback period. Obviously excel can be of great use in Capital Budgeting. Let us understand each of these concepts and its calculation in excel.
Net Present Value Net present value is the value of all future cash inflows less future cash outflows as on today. This is a major point in capital budgeting decisions. Net present value can be calculated in excel using two ways.
(a)
By calculating discounting factors – Consider the following example where project future cash flows are given for five years. In the year zero, i.e. beginning of year one, ` 1000 is shown as outflow, which is initial investment. Positive figures in year 2,3,4,5 shows net cash inflows. To calculate the discounted cash flow, discounting factor is calculated in row six. Row seven shows present value of cash flows. Cell F8 shows the net present value of all the future cash flows, i.e. ` 402.
Fig 6.10.1: Net Present value (b)
By using NPV function – A readymade function is available in excel for calculation of Net Present Value. The function NPV uses the syntax as under. Using NPV function, NPV can be directly calculated without calculating discounting factors. The following figure shows NPV calculation of cash flows for all the five years in ADVANCED INFORMATION TECHNOLOGY TRAINING
411
ADVANCE MS-EXCEL Cell L9. Formula bar below shows the syntax of NPV function.
Fig 6.10.2: NPV function
Internal Rate of Return: The discount rate often used in capital budgeting that makes the net present value of all cash flows from a particular project equal to zero. Generally speaking, the higher a project's internal rate of return, the more desirable it is to undertake the project. As such, IRR can be used to rank several prospective projects a firm is considering. Assuming all other factors are equal among the various projects, the project with the highest IRR would probably be considered the best and undertaken first. To calculate IRR using excel –
(a)
Click on function button and select IRR function as shown in Fig 6.10.3.
Fig 6.10.3: IRR function (b)
412
Following screen shall be displayed after selecting IRR function as shown in Fig 6.10.4.
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Fig 6.10.4: Screen display after selecting IRR function Values – Input the cash flow values here or give a range. Guess – Type any number that you guess is close to IRR. Here IRR is calculated as 23.29% as shown in Fig 6.10.5
Fig 6.10.5: Result of IRR function (c)
We can cross check this IRR by changing the Discount Rate in Cell D3 to 23.29%, automatically the Net Present Value becomes zero.
ADVANCED INFORMATION TECHNOLOGY TRAINING
413
ADVANCE MS-EXCEL
6.11 Risk Analysis & Investment Risk analysis is the process of defining and analyzing the dangers to individuals, businesses and government agencies posed by potential natural and human-caused adverse events. In quantitative risk analysis, an attempt is made to numerically determine the probabilities of various adverse events and the likely extent of the losses if a particular event takes place. Qualitative risk analysis, which is used more often, does not involve numerical probabilities or predictions of loss. Instead, the qualitative method involves defining the various threats, determining the extent of vulnerabilities and devising countermeasures should an attack occur. In case of investments, risk analysis is the study of the underlying uncertainty of a given course of investment action. Risk analysis refers to the uncertainty of forecasted future cash flows streams, variance of portfolio/stock returns, statistical analysis to determine the probability of a project's success or failure, and possible future economic states. Risk analysts often work in tandem with forecasting professionals to minimize future negative unforeseen effects. Almost all sorts of businesses require a minimum sort of risk analysis. For example, commercial banks need to properly hedge foreign exchange exposure of oversees loans while large department stores must factor in the possibility of reduced revenues due to a global recession. Risk analysis allows professionals to identify and mitigate risks, but not avoid them completely. Proper risk analysis often includes mathematical and statistical software programs.
Risk Analysis & Excel Excel being spreadsheet software can be very effectively used for analysis of any type of data and risk analysis cannot be an exception. There can variety of ways of using excel for risk analysis.
Risk Analysis Using Charts Charts are generally used to present information in a simple and better way. Charts can also be used to analyse the risk in a better way. Following figure shows how project, probability and its consequence can be explain in a simple and user friendly way using a chart as shown in Fig 6.11.1.
414
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Fig 6.11.1: Risk Analysis using Charts
Probability Probability is a measure of the likeliness that an event will occur. Probability is used to quantify an attitude of mind towards some proposition of whose truth we are not certain. The proposition of interest is usually of the form "Will a specific event occur?" The attitude of mind is of the form "How certain are we that the event will occur?" The certainty we adopt can be described in terms of a numerical measure and this number, between 0 and 1 (where 0 indicates impossibility and 1 indicates certainty), we call probability. Thus,higher the probability of an event, the more certain we are that the event will occur. A simple example would be the toss of a fair coin. Since the 2 outcomes are deemed equi-probable, the probability of "heads" equals the probability of "tails" and each probability is 1/2 or equivalently a 50% chance of either "heads" or "tails". Example 1:
Let us consider a case where we want to calculate probability of achieving sales target between 70 to 80 units. Follow the steps as under. 1.
Create two column headings in excel files as under Cell A1 – “Sales Units” Cell B1 – “Probability”
2.
Write the Sales Units in cells A2 to A7 as 50,60,70,80,90,100
3.
Write the probability of each number in front of it, i.e. in Cells B2 to B7 as 0.05, 0.1, 0.4, 0.3, 0.1 and 0.05.
4.
Get the cursor on Cell C2, i.e. the cell where we want to get the result.
5.
Click on Function key and select PROB function ADVANCED INFORMATION TECHNOLOGY TRAINING
415
ADVANCE MS-EXCEL 6.
Set as the variables as shown in the figure below.
Fig 6.11.2: Calculate probability 7.
Result will be generated in Cell C2 as “0.7”. It means that there are 70% chances of achieving sales target anything between 70 to 80 units.
Note: (a)
X-range – The range of sales units
(b)
Prob-range – The range of outcomes associates sales units.
(c)
Lower Limit – Here we wish to set it as 70, anything out of the sales units can be selected here.
(d)
Upper Limit – This field is optional. If ignored, it is considered as same as that of lower limit.
Example 2: Using the same data, calculate the probability of achieving sales level of anything ranging from 50 to 100. Solution: 1. Just click on Function Key once again and change the values of Lower & Upper Limit as 50 and 100 respectively. 2. Result generated is “1” or 100% if expressed in terms of percentage. It means, there are 100% chances of selling units between 50 to 100. In any case sales will not go below 50 units. This type of information is useful in taking various decisions, e.g. How much to spend on marketing, how many salesman to be appointed, what should be the price of the product, etc. In the similar way, probability of any particular outcome may be obtained just by changing lower and upper values.
416
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Sensitivity Analysis It is a technique used to determine how different values of an independent variable will impact a particular dependent variable under a given set of assumptions. This technique is used within specific boundaries that will depend on one or more input variables, such as the effect that changes in interest rates will have on a bond's price. Sensitivity analysis is a way to predict the outcome of a decision if a situation turns out to be different compared to the key predictions. Sensitivity analysis is very useful when attempting to determine the impact the actual outcome of a particular variable will have if it differs from what was previously assumed. By creating a given set of scenarios, the analyst can determine how changes in one variable will impact the target variable. Example 1:
Consider a simple case of loan and EMI calculation. In case of EMI calculations, there are two variables, loan amount and interest rate. Sensitivity analysis can be used to check the impact on the EMI if both the variables, i.e. loan amount and interest rates are changed. Input the data in excel sheet as under in Fig 6.11.3.
Fig 6.11.3: Sensitivity Analysis EMI in the above sheet is calculated using PMT function. Now, let us try to check the impact on EMI if interest rate varies from 7.5% to 9%. Also let us check the impact on EMI if loan amount changes from ` 15.00 Lacs to ` 50.00 Lacs. For this purpose, input the data as shown under. Interest rates are written in Cells A8:A23 and Loan Amounts are written in Cells C7:I7.
ADVANCED INFORMATION TECHNOLOGY TRAINING
417
ADVANCE MS-EXCEL
Fig 6.11.4: Sensitivity Analysis Using Two variable data Select the complete table from Cell A7 to Cell I23. Go to Data > What-If Analysis > Data Table
Fig 6.11.5: What-If Analysis Select the row input cell as the cell where loan amount is stored and select the column input cell as the cell where interest rate is stored and press enter.
418
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Following type of report shall be generated as shown in Fig 6.11.6.
Fig 6.11.6: Generated report It can be observed from the above table that in case of ` 30.00 lacs loan and rate of interest of 8% p.a., EMI comes to be ` 28,670, which matches with our original calculations. The complete data considering two variables is ready within few minutes.
Scenario Analysis Scenario is a particular situation dependent on some events. Scenario analysis includes analysis of a situation considering happening or not happening of certain events. In financial world, particularly regarding investments, it is the process of estimating the expected value of a portfolio after a given period of time, assuming specific changes in the values of the portfolio's securities or key factors that would affect security values, such as changes in the interest rate. Scenario analysis commonly focuses on estimating what a portfolio's value would decrease to if an unfavorable ADVANCED INFORMATION TECHNOLOGY TRAINING
419
ADVANCE MS-EXCEL event, or the "worst-case scenario", were realized. Scenario analysis involves computing different reinvestment rates for expected returns that are reinvested during the investment horizon. Example: Consider a case of a furniture shop. You have 100 chairs in your shop. Chairs are sold to different customer at different prices, e.g. ` 4,000 to ` 6,000. If we are selling 60% of chairs at highest price of ` 6,000 each and 40% chairs at lowest price of ` 4,000 each, following shall be the scenario.
Fig 6.11.7: Scenario Analysis ANow consider what if you are selling 70% of chairs at highest price, or 80% of chairs at highest price or 90% or all the chairs at highest price. What will be the profit figure in each case ? This can be easily done by using scenario analysis.
To create scenarios go to Data > What-If Analysis > Scenario Manager
Click on Add button
420
o
Type some relevant name for scenario
o
Link the changing cell, i.e. the cell where % (C3 in this case) is written and click on OK button.
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Fig 6.11.8: Edit Scenario After clicking OK button, scenario value has to set in this screen. Type 0.6 as value.
Fig 6.11.9: Scenario Value Go on creating all the scenarios one by one for 70%, 80% 90% and 100%. To see the changes in report, change the scenario and click on show button in Scenario Manager screen. Note: Cell having % and number of chairs sold must be linked.
Certainty Equivalent Model Certainty Equivalent can be considered as a guaranteed return that someone would accept, rather than taking a chance on a higher, but uncertain, return. If you've ever thought about leaving your job to start your own profession, and potentially make more money, but decided to stay and continue drawing a salary instead, then the amount of your salary is your certainty equivalent. You might need to come up with a business idea with a higher potential payoff to be convinced to leave the security of your existing job. Investments must pay a risk premium to compensate investors for the possibility that they may not get their money back. If an investor has a choice between a Government bond paying 3% interest and a corporate bond paying 8% interest, and he chooses the government bond, the payoff is the certainty equivalent. The company would need to offer this particular investor a potential return of more than 8% on its bonds, to convince him to ADVANCED INFORMATION TECHNOLOGY TRAINING
421
ADVANCE MS-EXCEL buy. Thus, a company seeking investors can use the certainty equivalent as a basis for determining how much more it needs to pay, to convince investors to consider the riskier option. The certainty equivalent will vary, because each investor has a unique risk tolerance.
Decision Tree Analysis It is a system where a schematic tree-shaped diagram is used to determine a course of action or show a statistical probability. Each branch of the decision tree represents a possible decision or occurrence. The tree structure shows how one choice leads to the next, and the use of branches indicates that each option is mutually exclusive. A decision tree can be used to clarify and find an answer to a complex problem. The structure allows users to take a problem with multiple possible solutions and display it in a simple, easy-to-understand format that shows the relationship between different events or decisions. The furthest branches on the tree represent possible end results. A decision tree is a kind of flowchart -- a graphical representation of the process for making a decision or a series of decisions. Businesses use them to determine company policy, sometimes simply for choosing what policy is, other times as a published tool for their employees. Individuals can use decision trees to help them make difficult decisions by reducing them to a series of simpler, or less emotionally laden, choices. Regardless of the context or type of decision, the structure of a decision tree remains the same. Or you can say A decision tree is a decision support tool that uses a tree-like graph or model of decisions and their possible consequences, including chance event outcomes, resource costs, and utility. It is one way to display an algorithm. Example: How to create a decision tree in excel? Follow the steps as given here. 1.
Open a new excel file and go to the "Insert" tab and click the "SmartArt" button. A window titled "Choose a SmartArt Graphic" will appear. Click the "Hierarchy" category and choose "Horizontal Labeled Hierarchy" design. Click "OK."
2.
Type the name of the decision next to the first bullet point in the window that says "Type your text here." Type something like "Investment," if you are making an investment decision.
3.
Type the names of each option in the indented bullet points under the decision bullet. For example, you are investing in a lump sum amount either with Government or in a private company. Evaluate each option and determine whether a result is achieved, if there is uncertainty, or if another decision needs to be made
4.
Insert boxes wherever there is another decision to be made and circles for uncertainties. If there is a result, nothing needs to be done. Boxes can be added by pressing "Enter" and "Tab" after the bullet point where you would like to add a box. To change the shape to a circle, for example, right click on the shape, and select "Change Shape." Select a circle.
422
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL 5.
Enter probabilities in the closest cell where circles and lines join. The probabilities represent the percentage you expect to occur. Enter estimated values such as dollar values in the closest cell where boxes and lines are joined. These represent the estimated value of the decision if it is taken.
A sample decision tree can be prepared as shown in Fig 6.11.10.
Fig 6.11.10: Sample decision tree While considering an investment option, safety of money, returns and liquidity may be the criteria for evaluating each investment option.
Monte Carlo Simulation A problem solving technique used to approximate the probability of certain outcomes by running multiple trial runs, called simulations, using random variables. Monte Carlo simulation is named after the city in Monaco, where the primary attractions are casinos that have games of chance. Gambling games, like roulette, dice, and slot machines, exhibit random behavior. Monte Carlo simulation is a computerized mathematical technique that allows people to account for risk in quantitative analysis and decision making. The technique is used by professionals in such widely disparate fields as finance, project management, energy, manufacturing, engineering, research and development, insurance, oil & gas, transportation, and the environment. Monte Carlo simulation furnishes the decision-maker with a range of possible outcomes and the probabilities they will occur for any choice of action.. It shows the extreme possibilities—the outcomes of going for broke and ADVANCED INFORMATION TECHNOLOGY TRAINING
423
ADVANCE MS-EXCEL for the most conservative decision—along with all possible consequences for middle-of-the-road decisions. The technique was first used by scientists working on the atom bomb; it was named for Monte Carlo, the Monaco resort town renowned for its casinos. Since its introduction in World War II, Monte Carlo simulation has been used to model a variety of physical and conceptual systems.
6.12 Finance Planning Planning is considered to be the primary requirement for moving towards any goal. Financial planning is the process of meeting the financial goals through the proper management of finances. Proper management of finances includes deciding the source and application of funds along with it timing. It is common for anybody to face financial setbacks at some point. One way to avoid or reduce the impact of such setbacks in the future is through careful financial planning. Financial goals can include buying a home, saving for your child’s education or planning for retirement. The financial planning process involves the following steps: There are two basic rules in any type of financial planning.
(a)
Earlier the better – Money received today is always better than money received tomorrow.
(b)
Bigger the better – More money received is always better than less money received.
Five Ds of Finance Planning: 1. Deciding the Objective : This is the first step in financial planning. One has to be clear about the objective of finance planning. This is basic step which decides and impacts all the future steps. 2. Data Collection : Once the objective is decided and clear, the next step is to collect the required data for analysis. Data can be obtained in any form, but mostly it will be in figures. Excel can be used for storing the data of any size very easily. 3. Data Analysis : This is a very important step in the overall process. This step requires huge amount of efforts and expertise. Excel can be very effectively used for analysis of data of any size and that too with great amount of ease. Data is evaluated as per the direction of financial objective. 4. Drawing Inference :This step invovles human intervention. Many a times this step is ignored. Every individual may have his/her own set of rules for drawing inferences. Two different individuals may draw two different inferences using the same set of data. 5. Decision Making : Once the inferenace is drawn, decision has to be taken about financial planning. Decision making involves taking action on the basis of four earlier steps.
424
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Deciding the Objective
Data Collection
Data Analysis
Drawing Inference
Decision Making
Fig 6.12.1: Five Ds of Finance Planning
Using Excel for Financial Planning Various excel functions and features can be used in the process of financial planning. Some of the functions are listed below. Sr. No.
Function
Use
1
PMT
Payment – Used for calculating monthly installment/investment amount.
2
PPMT
Principal Payment – Used for calculating principal amount in EMI
3
IPMT
Interest Payment – Used for calculating interest amount in EMI
4
FV
Future Value – Used for calculating future value of present investment
5
RATE
Rate – Used for calculating rate of interest
6
NPER
Number of Periods – Used for calculating number of periods (months/years) required for a particular maturity amount at a given rate of interest.
7
IRR
Internal Rate of Return – Used for
8
PV
Present Value – Used for calculating present value of future cash flows.
Table 6.12.1 Excel function for Financial Planning
ADVANCED INFORMATION TECHNOLOGY TRAINING
425
ADVANCE MS-EXCEL
6.13 Personal Financial Planning Personal financial planning in case of most of the individuals shall include planning for retirement, decision about home loans, budgeting for major expenses like marriage of children, education expenses, etc. Let us directly try to handle these commonly asked questions by individuals. Example 1: Mr. Swapnil Ghate is willing to invest ` 5,000 per month for the purpose of buying office space. He wants to know how much amount he would get at the end of 10 years considering a rate of interest of 8% p.a. Solution: This question can be answered very easily by using “FV” function. Following shown in Fig 6.13.1 how this function can be used.
Fig 6.13.1: FV Function Please Note: (a)
Period is given in months and rate of interest is given per anum. Here, while linking the rate interest, it should be divided by 12 to arrive at the monthly rate of interest.
(b)
All outflows shall be considered as a negative figure as per excel norms. Hence monthly investment of ` 5,000 is written as negative figure.
Here the answer is appearing as ` 9,14,730. Example 2: Mr. Ashish Deshpande is planning to have ` 10.00 Lacs after five years for the purpose of education of his daughter. He wants to know how much he needs to invest every month considering a rate of interest of 8% p.a. 426
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Solution: This question can be answered using two combination of two functions PMT and FV. Look at the figure shown below. We have used PMT function and set the future value as ` 10.00 Lacs. The result shown is ` 13,610 as shown in Fig 6.13.2.
Fig 6.13.2: PMT Function with Future Value Example 3:
Mr. Amit Shriwas want to have ` 5.00 lacs at the end of five years by investing ` 5,000 per month. He wants to know the rate of interest at which he should invest. Solution:
This question can be answered using RATE function and future value.
ADVANCED INFORMATION TECHNOLOGY TRAINING
427
ADVANCE MS-EXCEL
Fig 6.13.3: Rate Function with Future Value As shown in the figure above, Mr. Amit Shriwas needs to invest ` 5,000 per month for 60 months @ 1.62% p.m., i.e. @ 19.38% p.a. Example 4 : Ms. MayuraRahane is interest in investing ` 10,000 per month @ 10% p.a. She wants ` 5.00 Lacs for the purchase of a plot. She is interested in knowing the period for which she should invest to get ` 5.00 Lacs. Solution: This question can be answered using NPER function with future value as shown in Fig 6.1.3.4.
Fig 6.13.4: NPER Function 428
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL The answer is 41.97 Months.
6.14 Corporate Financial Planning Basic rules of personal financial planning and corporate financial planning are same. The difference is in the quantum of money involved. As it is very high as compared to the money involved in personal financial planning, the amount of risk involved becomes very high. The amount of risk involved is also affected by the various other factors like changes in business conditions, technology, Government policies, international issues, etc. Corporate planning can be defined as the process of setting the procedures in the organization for achieving the predefined goals. A corporate plan should incorporate the values and priorities of a company, with a comprehensive map of how to achieve those goals. The growth of a business depends on many factors like good leadership, a product or service in high demand etc but the most important is careful financial planning. The process of planning includes – 1.
Research/ study of the existing situation.
2.
Analysis about present resources and liabilities for an entity.
3.
Goal Setting
4.
Prioritisation of goals
5.
Incorporate budget details into a feasible plan for the future.
6.
Utilisation of existing resources for achievement of the goals.
7.
Comparison of planned activities VS actual results at regular period of time.
Technological advancements play a vital role in financial planning at the corporate level. These advancements include usage of various software, comparison of periodical information, discussions among top management, passing of crystal clear goals before each and every individual, etc. Obviously excel can play an important role for corporate financial planning. Various formats can be prepared using functions / feature in excel. Following are some activities which are being carried out in the process of corporate financial planning. 1.
Analysis of Financial Statements
2.
Forecasting of Annual Revenues
3.
Turning Points in Financial Trends
4.
Forecasting Financial Statements
5.
Forecasting seasonal revenues
6.
Cash Budgeting
7.
Calculation of NPV, IRR etc
8.
Calculation of Cost of Capital ADVANCED INFORMATION TECHNOLOGY TRAINING
429
ADVANCE MS-EXCEL 9.
Calculations of Break Even Points, Profit and Leverage etc
10.
Calculation Depreciation and taxes
11.
Capital Budgeting and so on
From above we get an overall idea what the corporate financial planning is and how it is being done.Many of the above stated features are explained earlier. Let us discuss some of the issues regarding financial planning and excel. Example 1: Iterative Calculations Indradhanu Consulting Pvt. Ltd. is planning to avail a term loan of ` 10.00 crores for a term of 10 years at 10% rate of interest p.a. For the purpose of preparation of financial plan for 10 years, they wish to calculate interest on average balance. Prepare a chart showing interest calculation and repayment. Solution: A simple chart can be prepared as shown in Fig 6.14.1(A).
Fig 6.14.1(A): Iterative Calculations In the above chart, we have calculated principal closing balance. This is not loan closing balance as interest payable is yet to be calculated. Please note that interest shall be calculated on average balance of loan and average balance shall be calculated as opening balance + closing balance divided by two. The basic problem here is that we need to calculate interest for getting closing balance figure and at the same time closing balance figure is needed to calculate average balance, which is in turn used for calculation of interest. Hence, closing balance is needed for interest calculation and interest figure is needed for closing balance calculation. This question problem is just like “What Comes First ? Egg or Hen ? “ This problem can be solved by using Iterative Calculations in excel. Iterative calculation is a feature where calculation is performed in a loop automatically for required number of times. The result is displayed when the change in calculation is negligible. Please note:
In year 1, before considering the interest figure, average balance is (1000 + 900) /2 = 950
Interest shall be calculated on this average balance @ 10%, i.e. 95.
This 95 shall be added to the outstanding, closing balance shall increase to 995.
Again the average balance shall be calculated considering the closing balance of 995.
430
ADVANCED INFORMATION TECHNOLOGY TRAINING
APPLICATION OF MS-EXCEL
Now, the average balance shall be 997.50 and interest on this figure shall be 99.75.
This process shall be repeated till the time the change between the two calculations is negligible.
Calculating the interest to calculate average balance and vice versa is called as iterations.
This can be done manually, as it is done in the sheet below. But it would take lot time.
Fig 6.14.1(B): Iterative Calculations In the above figure, all the calculations are for year 1 only. So ultimately we have settled on the interest figure of 100.00 Above type of iterative calculations can be very easily done using excel using following simple steps.
Prepare a chart as shown above.
Calculate the average balance.
Calculate interest on average balance.
Link this interest figure with Cell B4.
As soon as you press ENTER to accept interest calculation, a Circular Reference Warning message is displayed. Excel assumes that something has gone wrong.
Here, we need to tell excel that this is the way we wish to calculate interest and nothing has gone wrong. This can be done by making a small change as under.
Click on File and go to Options.
Go to Formulas.
ADVANCED INFORMATION TECHNOLOGY TRAINING
431
ADVANCE MS-EXCEL
Fig 6.14.2: Excel Option
Check the check box for “Enable iterative calculation”. Maximum iterations and maximum change figures can be specified here. Now onwards, excel shall not display any Circular Reference Warning Error Message.
The completed chart shall look as shown in Fig 6.14.3.
Fig 6.14.3: Complete Chart In the above case, we have assumed that interest is paid separately. Every single feature in excel can be used in variety of ways. Its use is limited by the imagination of the user only. The list of features and functions is just an illustrative list and not an exhaustive list.
432
ADVANCED INFORMATION TECHNOLOGY TRAINING