Working with database in excel

Any database (DB) is a summary table with the parameters and information. Most schools programs included the creation of a database in Microsoft Access. But Excel gives all the opportunities to build simple databases and easily navigate through them.

How to make the database in Excel so it was convenient not to only store but also process the data: generate reports, build charts, graphs, etc.



Step by step to create a database in Excel

At first we will learn how to create a database using Excel tools. Let’s imagine that we are the shop. We draw up a summary table of data with various products deliveries from different suppliers.

Product Product Category Quantity Price kg Total value Delivery month Supplier Who accepted items

We puzzled out with headlines. Now fill the table. We start with a serial number. We don’t have to put down the numbers manually. Enter in cells A4 and A5 one and two respectively. Then select those two cells with left mouse button and grab the corner of the segregation and extend down to any number of rows. In a small little window you will see the final number.

Fill the table.

Note. This table can be downloaded at the end of the article.

Base show us that some of the information will be presented in text form (product, category, month, etc.), and some is in the financial. Select the cells with the headlines named Price kg and Total value E4:F23. Use right-click to see context menu where choose «Format Cells» CTRL+1.

A window will appear where we will choose the Currency format. Enter the number of decimal places equals 1. We don’t have to choose designation because in the header we already pointed out that the price and value in $ English (United States).

$ English (United States).

Similarly we proceed with the cells where the quantity column will be filled. Select numerical number.

Let’s deal with another preparatory action. You can immediately use that fact that in the corresponding cells value is calculated as the price multiplied by the quantity. To make this we enter in cell F4 formula and stretch it to the other cells in this column. Thus the cost will be calculated automatically while filling the table.

automatically while filling the table.

Now fill the table with data.

It’s important! It is necessary to stick to a single style of writing while filling the cells. If the original name of the employee is recorded as Alex AA, then the rest cells should be filled similarly. The work with the database will be difficult if somewhere name will be written differently, for example, Alexey Alex.

The table is ready. In reality it may be much longer. We have added a several positions for example. Let us give the database a more aesthetic appearance with making the frame. To do this select the entire table and find the parameter «All Borders» on the panel.

All Borders.

Similarly, frame the headlines thick outer boundary.



Excel functions for working with database

Now we turn to the functions that Excel offers to work with the database.

Working with databases in Excel

Example: we want to know all the products receipted by Alex AA Theoretically, you can run through the all rows visually where this name appears and then copy them to a separate table. But what if our database composed of several hundreds of items? FILTER comes to help us.

Select all the headlines in the table and click «FILTER» in the «DATA» tab, (CTRL + SHIFT + L).

FILTER.

In each cell in the header appears black arrow on a gray background which can be clicked to filter the data. Click it in the parameter WHO ACCEPTED ITEMS and remove the check mark from the CAROLINE name.

CAROLINE.

Thus there are remains data only with Alex.

Alex.

Note! When you are sorting data not only all the positions in the columns stays in its places but rows of numbers also corresponding to the sheet (these are highlighted in blue). This feature is useful to us later.

You can make additional filtering. Determine which kind of grouts Alex accepted. Click the arrow on the cell PRODUCT CATEGORIY and leave only grouts.

PRODUCT CATEGORIY.

If you need to return the full database you can make it in easiest way: set out all the checkboxes in the corresponding filters.

Data sorting

In this example the database was filled in chronological order during the supplying goods in the shop. But if we want to sort the data on a different principle excel allows you to do that too.

For example, we want to sort the products as price increase. Those the first line will be the cheapest product and in the last will be the most expensive. Select the column with the price and on the HOME tab and choose the «Sort & Filter».

Sort & Filter.

As we decided that lower price would be on top choose «Sort Smallest to Largest». You will see another window where we select «Expand the selection», so the other columns can also adjust to the sorting.

We see that the data is sorted in order to increasing price.

increasing price.

Note! You can make sorting in order to increase or decrease parameter using AutoFilter. Such action is also proposed when you press the arrow.

Sort by condition

We need to extract from the database products that were purchased in lots of 25 kg or more. For this purpose click the filter arrow on QUANTITY cell, and select the following options.

QUANTITY.

In the window that appears in front of condition БОЛЬШЕ ИЛИ РАВНО inscribe number 25. Then you will get sample indicating the products ordered by the lots greater than 25 kg or equal to this. Those products also sorted in the manner of its price growth since we did not remove sorting by price.

prices.

Subtotals

This is another useful function which allows calculating the sum, the multiplication, minimum or average value, etc. using the existing database. It is called the subtotals. =SUBTOTAL() This function has one main advantage. It allows making calculations with certain function even if you change the size of the table. Let’s consider it with an example.

Let us give our full database suitable view. Next we create a formula for the AutoSum in column Total value. Enter formula writing it in the F26 cell. At the same time remember how database sorting in Excel: number of rows fixed in place. Therefore the formula will still be in the F26 cell even when we do filtering.

cell even when we do filtering.

Subtotal function has 30 arguments. The first is static: the action code. By default Excel set code number 9, so let it be. The second and subsequent arguments are dynamic: this is links to ranges which are summed up. We have a range: F4: F24. It turned out 19,670 rubles.

Now try again to sort number, leaving only a party of 25 kg and >.

only a party of 25 kg.

We see that the amount has changed, too.

download example

In Excel, you can also create a small database and easy to work with them. When large volumes of data is very convenient and efficient.

Plug into your data

Northwind Trading Company, a small wholesale food business, is doing quite well since they moved online. Retail merchants across the country buy everything  from salmon to granola and have it shipped quickly to their stores.

Their customer information is stored in an Access database, and now, the marketing team needs a better way to view it. In particular, they are interested in seeing where their customers reside so they can more effectively target their advertising dollars.

Excel icon

Create a data connection between Excel and Access

Luckily, the same features that Excel provides for viewing and organizing information in a spreadsheet, such as filtering, charting, and grouping, can be used to view and organize information in an Access database. But first you need to create the connection.

Note: We’ll use the sample Northwind Access database to demonstrate how Excel connects to data sources. You can download it here:  Northwind Web Database.

1. Go to the Data tab in Excel and click the From Access button.

2. On the Select Data Source dialog, go to the location where the Access database is stored, select it, and click the Open button

3. On the Select Table dialog, choose a table from the database to import.

4. Accept the default options on the Import Data dialog, and click OK.

Excel and Access are now connected, and the data from the Northwind CustomersExtended table appears in Excel.

Refresh data

Now that Northwind can now easily view and analyze the information in its Access database, they want to make sure they are reviewing the latest information.There’s a couple ways they can refresh the data in their workbook.

Forced Refresh

To force a refresh, click the Refresh All button on the Data tab. This will instantly import the latest Access data into Excel.

Customized Refresh

Northwind can customize the refresh behavior for their workbook in the following ways:

  • Enable background refresh (this option allows them to continue working in Excel while the refresh operation executes).
  • Refresh data after a specified time period (e.g. every 30 minutes)
  • Refresh data when opening a workbook

1. Click the Connections button on the Data tab, and then click the Properties button on the Workbook Connections dialog.

2. On the Connection Properties dialog, select the desired Refresh control options and click OK.

All connected!

Northwind can now make better advertising decisions. Currently, they don’t have a single order from New York for their very popular gnocchi, and so they decide to focus their advertising on the the tratorrias of Little Italy.

database function in excel

Database Function in Excel (Table of Contents)

  • Introduction to Database Function in Excel
  • How to Use Database Function in Excel?

Introduction to Database Function in Excel

Excel database functions are designed in such a way that a user can use an Excel database to perform the basic operation on it like Sum, Average, Count, Deviation, etc. The database function is an in-built function in MS Excel that will work only on the proper database or table. These functions can be used with some criteria also.

Syntax: 

database function in excel 

There are some specific in-built Database Functions which are listed below:

  • DAVERAGE: It will return the average of the selected database, which is satisfying the user criteria.
  • DCOUNT: It will count the cells containing some number in the selected database and satisfy the user criteria.
  • DCOUNTA: It will count the non-blank cells in the selected database and which is satisfying the user criteria.
  • DGET: It will return a single value from the selected database, which is satisfying the user criteria.
  • DMAX: It will return the maximum value of the selected database, which is satisfying the user criteria.
  • DMIN: It will return the minimum value of the selected database, which is satisfying the user criteria.
  • DPRODUCT: It will return the multiplication output of the selected database, which is satisfying the user criteria.
  • DSTDEV: It will return the estimated standard deviation of the population based on the entire population in the selected database, which is satisfying the user criteria.
  • DSTDEVP: It will return the standard deviation of the entire population based on the selected database, which is satisfying the user criteria.
  • DSUM: It will return the summation of the value from the selected database, which is satisfying the user criteria.
  • DVAR: It will return the estimated variance of the population based on the entire population in the selected database, which is satisfying the user criteria.
  • DVARP: It will return the Estimates variance of the entire population in the selected database, which is satisfying the user criteria. 

How to Use Database Functions in Excel?

Database Functions in Excel is very simple and easy. Let’s understand how to use the Database Functions in Excel with some examples.

You can download this Database Function Excel Template here – Database Function Excel Template

Example #1 – Using DAVERAGE Database Function in Excel

Let’s assume a user has some people’s personal data like Name and Age, where the user wants to calculate the average age of the people in the database. Let’s see how we can do this with the DAVERAGE function.

Open MS Excel from the Start menu, Go to Sheet where the user has kept the data.

database function in excel example 1-1

Now create headers for DAVERAGE result where we will calculate the average of the people.

database function in excel example 1-2

Now calculate the DAVERAGE of the given data by DAVERAGE function, use the equal sign to calculate, Write in C2 Cell.

database function in excel example 1-3

It will then ask for the database given in A1 to B10 cell, select A1 to B10 cell.

database function in excel example 1-4

Now it will ask for the Age, so select C1 cell.

database function in excel example 1-5

It will then ask for criteria from B2 to B10 cell where the condition will be applied and select B2 to B10 cell.

database function in excel example 1-6

Press the Enter Key.

database function in excel example 1-7

Summary of Example 1: As the user wants to calculate the average age of the people in the database. Everything is calculated in the above excel example, and the Average age is 13 for the group. 

Example #2 – Use of DMAX and DMIN Database Function in Excel

Let’s assume a user has few personal data, like Name and Age, where the user wants to find out the maximum and minimum age of the people in the database. Let’s see how we can do this with the DMAX and DMIN function. Open MS Excel from the Start menu, Go to Sheet where the user kept the data.

DMAX and DMIN 1-1

Now create headers for DMAX and DMIN results where we will calculate the maximum and minimum age of the people.

DMAX and DMIN 1-2

Now calculate the maximum age in the given age data by DMAX function, use the equal sign to calculate, Write in a formula in cell C2.

DMAX and DMIN 1-3

It will then ask for the database given in cell A1 to B10 and select cell A1 to B10.

 DMAX and DMIN 1-4 

Now it will ask for Age, select B1 cell.

DMAX and DMIN 1-5

Now it will ask for criteria which are cells B2 to B10 where the condition will be applied, select cell B2 to B10.

DMAX and DMIN 1-6

Press the Enter Key.

DMAX and DMIN 1-7

Now to find out the minimum age, use the DMAX function and follow steps 4 to 7. Use the DMIN formula.

DMAX and DMIN 1-8

Summary of Example 2: As the user wants to find out the maximum and minimum age of the people in the database. Easley everything calculated in the above excel example and the Maximum age is 20, and the minimum is 8 for the group.

Example #3 – Use of DCOUNT and DCOUNTA Database Function in Excel

A user wants to find out the numeric data count and nonblank cell count in the height column in the database. Let’s see how we can do this with the DCOUNT and DCOUNTA function. Open MS Excel from the Start menu; go to Sheet3, where the user kept the data.

database example 3-1

Now create headers for DCOUNT and DCOUNTA results.

database example 3-2

Write the formula in cell D2.

database in excel 3-2

It will then ask for the database given in cell A1 to C10 and select cell A1 to C10.

database excel 3-3 

Now it will ask for the Height, select cell B1.

database excel 3-4

Now it will ask for criteria which are cell B2 to B10, where the condition will be applied, select cell B2 to B10.

database excel 3-5

Press Enter key.

database excel 3-6

Now to find out nonblank cell function follow steps 4 to 7. Use the DCOUNTA formula.

database excel 3-7

Summary of Example 3: As the user wants to find out the numeric data count and nonblank cell count in the height column. Easley everything calculated in the above excel example, the numeric data count is 7, and the nonblank cell count is 9. 

Things to Remember About Database Functions in Excel

  • All database functions follow the same syntax, and it has 3 arguments: a database, field, and criteria.
  • Database function will work only if the database has a proper table format like it should have a header.

Recommended Articles

This is a guide to Database Function in Excel. Here we discuss how to use Database Function in Excel along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. Excel Create Database
  2. Excel Database Template
  3. User-Defined Function in Excel
  4. PRODUCT Function in Excel

Excel is a combination of rows and columns, and these rows and columns store our data, which in other terms are named records. As Excel is the most common tool, we reserve the data in Excel, making it a database. Therefore, when we put data in Excel in some form of tables in rows and columns and give the table a name, that is a database in Excel. We can also import data from other sources in Excel, given the data format is proper with the Excel format.

For example, you may create a company’s sales report of different regions on a database in Excel for easy access and complete control over data management while working with the program.

Creating an Excel Database

Having the data in Excel will make life easier for you because Excel is a powerful tool where we can play with the data. If you maintain the data in other sources, you may not correctly get all the formulas, dates, and time format. I hope you have experienced this in your daily work. Having the data in the right database platform is very important. Having the data in Excel has its pros and cons. However, if you are a regular user of Excel, it is much easier to work with Excel. This article will show you how to create a database in Excel.

Table of contents
  • Creating an Excel Database
    • How to Create a Database in Excel?
    • Things to Remember While Creating a Database in Excel
    • Recommended Articles

Database in Excel

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: Database in Excel (wallstreetmojo.com)

How to Create a Database in Excel?

We do not see any of the schools are colleges teaching us to Excel as the software in our academics. Whatever business models, we learn a theory until joining the corporate company.

The biggest problem with this theoretical knowledge is it does not support real-time life examples. But, nothing to worry about; we will guide you through the process of creating a database in Excel.

We need to design the Excel worksheet carefully to have accurate data in the database format.

You can download this Create Database Excel Template here – Create Database Excel Template

Follow the below steps to create a database in Excel.

  1. We must first ensure all the required columns and name each heading properly.

    create excel database 1.1

  2. Once the headers of the data table are clear, we can easily start entering the data just below the respective column headings.

    create excel database 1.2

    In database terminology, rows are called Records, and columns are called Fields.

  3. We cannot leave a single row empty when entering the data. For example, we have entered the headings in the first row, and if we start entering the data from the third row by leaving the 2nd row empty, we are gone.

    create excel database 1.3

    Not only the first or second row, but we also cannot leave any row empty after entering certain data into the database field.

  4. As we said, each column is called Fields in the database. Similarly, we cannot have an empty field between the data.

    We need to enter the fields one after the other. Having a gap of even one column or field is strictly prohibited.

    create excel database 1.4

    I am so stressed about not having an empty record or field because when the data needs to be exported to other software or the web, as soon as the software sees the blank record or field, it assumes that it is the end of the data. Therefore, it may not consider the full data.

  5. We must fill in all the data carefully.

    create excel database 1.2
    In the above image, I have data all the way from row 1 to row 5001.

  6. The final thing we need to do is convert this data to an excel table. By selecting the data, press Ctrl + T.

    create excel database 1.5

  7. Here, we need to make sure the My table has a header checkbox is ticked and the range is selected properly.

    create excel database 1.6

  8. Then, we must click on OK to complete the table creation. As a result, we may have a table like this now.

    create excel database 1.7

  9. We must now give a proper name to the table under the table Design tab.

    create excel database 1.8

  10. Since we have created a table, automatically, it would expand whenever we enter the data after the last column.

    We have the database ready now. Follow the pros and cons below to have a good hand on your database.

Things to Remember While Creating a Database in Excel

  • We can upload the file to MS Access to have a secure database and back up a platform.
  • Since we have all the data in Excel, it is very easy for your calculations and statistics.
  • Excel is the best tool for database analysis.
  • Easy to read and not complicated because of clear fields and records.
  • We can filter out the records by using auto filters.
  • If possible, sort the data according to date-wise.
  • As the data keeps growing, Excel will slow down considerably.
  • We cannot share more than 34 MB files with others in an email.
  • We can Apply the Pivot tableA Pivot Table is an Excel tool that allows you to extract data in a preferred format (dashboard/reports) from large data sets contained within a worksheet. It can summarize, sort, group, and reorganize data, as well as execute other complex calculations on it.read more and give a detailed analysis of the database.
  • We can download the workbook and use it for your practice purpose.

Recommended Articles

This article is a guide to Databases in Excel. Here, we discuss creating a database in Excel with examples and downloadable Excel templates. You may also look at these useful functions in Excel: –

  • Excel Database Template
  • Match Data using Excel Functions
  • Forms for Data Entry in Excel
  • Create a Data Table in Excel
  • SUMIFS with Dates

Do you need to create and use a database? This post is going to show you how to make a database in Microsoft Excel.

Excel is the most common data tool used in businesses and personal productivity across the world.

Since Excel is so widely used and available, it tends to get used frequently to store and manage data as a makeshift database. This is especially true with small businesses since there is no budget or expertise available for more suitable tools.

This post will show you what a database is and the best practices you should follow if you’re going to try and use Excel as a database.

Get the example files used in this post with the above link and follow along below!

What is a Database?

A database is a structured set of data that is often in an electronic format and is used to organize, store. and retrieve data.

For example, a database might be used to store customer names, addresses, orders, and product information.

Databases often have key features that make them an ideal place to store your data.

Database vs Excel

An Excel spreadsheet is not a database, but it does have a lot of great and easy-to-use features for working with data.

Here are some of the key features of a database and how they compare to an Excel file.

Feature Database Excel
Create, read, update, and delete records ✔️ ✔️ Excel allows anyone to add or edit data. This can be viewed as a negative consideration.
Data types ✔️ ⚠️ Excel allows for simple data types such as text, numbers, dates, boolean, images, and error values. But lacks more complex data types such as date and timezones, files, or JSON.
Data validation ✔️ ⚠️ Excel has some data validation features, but you can only apply one rule at a time and these can easily be overridden on purpose or by accident.
Access and security ✔️ ❌ Excel doesn’t have any access or security controls. This is usually managed through your on-premise network or through SharePoint online. But anyone can access your Excel file if it’s downloaded and sent to them.
Version control ✔️ ❌ Excel has no version control. This can be managed through SharePoint.
Backups ✔️ ❌ Excel has no automated backups. These can be manually created or automated in SharePoint.
Extract and query data ✔️ ✔️ Excel allows you to extract and query data through Power Query which is easy to learn and use.
Perform calculations ✔️ ✔️ Excel has a large library of functions that can be used in calculated columns inside tables. Excel also has the DAX formula language for calculated columns in Power Pivot.
Aggregate and summarize data ✔️ ✔️ Excel can easily aggregate and summarize data with formulas, pivot tables, or power pivots.
Relationships ✔️ ✔️ Excel has many lookup functions such as XLOOKUP, as well as table merge functionality in Power Query, and 1 to many relationships in Power Pivot.
Scale with large amounts of data ✔️ ⚠️ Excel can hold up to 1,048,576 rows of data in a single sheet. Tools like Power Query and Power Pivot can help you deal with larger amounts of data but they will be constrained based on your hardware specifications.
User friendly ❌ A database might not be user-friendly and may come with a steep learning curve that your intended users won’t be able to handle. ✔️ Most people have some experience with using Excel.
Cost ❌ Can be expensive to set up, run, and maintain a proper database tool. ✔️ Your organization might already have access to and use Excel.

This is not a comprehensive list of features that a database will have, but they are some of the major features that will usually make a proper database a more suitable option.

The features that a database has depends on what database it is. Not all databases have the same features and functionality.

You will need to decide what features are essential for your situation in order to decide if you should use Excel or some other database tool.

💡 Tip: If you have Excel for Microsoft 365, then consider using Dataverse for Teams as your database instead of Excel. Dataverse has many of the great database features mentioned above and it is included in your Microsoft 365 license at no additional cost.

Relational Database Design

A good deal of thought should happen about the structure of your database before you begin to build it. This can save you a lot of headaches later on.

Most databases have a relational design. This means the database contains many related tables instead of one table that contains all the data.

Suppose you want to track orders in your database.

One option is to create a single flat table that contains all the information about the order, the products, and the customer that created the order.

This isn’t very efficient as you end up creating multiple entries of the same customer information such as name, email, and address. You can see in the above data, column G, H, and I contains a lot of duplicate values.

A better option is to create separate tables to store the Order, Product, and Customer data.

The Order data can then reference a unique identifier in the Product and Customer data that will relate the tables and avoid unnecessary duplicate data entry.

This same example data might look like this when reorganized into multiple related tables.

  1. An Orders table that contains the Item and Customer ID field.
  2. A Products table that relates to the Item fields in the Orders table.
  3. A Customers table that relates to the Customer ID in the Orders table.

This avoids duplicated data entry in a flat single table structure and you can use the Item or Customer ID unique identifier to look up the related data in the respective Products or Customers tables.

Tabular Data Structure in Excel

If you’re going to use Excel as your database, then you’re going to need your data in tabular format. This refers to the way the data is structured.

The above example shows a product order dataset in tabular format. A tabular data format is best suited for Excel due to the row and column structure of a spreadsheet.

Here are a few rules your data should follow so that it’s in tabular format.

  • 1st row should contain column headings. This is just a short and descriptive name for the data contained below.
  • No blank column headings. Every column of data should have a name.
  • No blank columns or blank rows. Blank values within a field are ok, but columns or rows that are entirely blank should be removed.
  • No subtotals or grand totals within the data.
  • One row should represent exactly one record of data.
  • One column should contain exactly one type of data.

In the above orders example data, you can see B2:E2 contains the column headings of an Order ID, Customer ID, Order Date, Item, and Quantity.

The dataset has no blank rows or columns, and no subtotals are included.

Each row in the dataset represents an order for one type of product.

You’ll also notice each column contains one type of data. For example, the Item column only contains information on the name of the product and does not include other product information such as the price.

⚠️ Warning: If you don’t adhere to this type of structure for your data, then summarizing and analyzing your data will be more difficult later. Tools such as pivot tables require tabular data!

Use Excel Tables to Store Data

Excel has a feature that is specifically for storing your tabular data.

An Excel Table is a container for your tabular datasets. They help keep all the same data together in one object with many other benefits.

💡 Tip: Check out this post to learn more about all the amazing features of Excel Tables.

You will definitely want to use a table to store and organize any data table that will be a part of your dataset.

How to Create an Excel Table

Follow these steps to create a table from an existing set of data.

  1. Select any cell inside your dataset.
  2. Go to the Insert tab in the ribbon.
  3. Select the Table command.

This will open the Create Table menu where you will be able to select the range containing your data.

When you select a cell inside your data before using the Table command, Excel will guess the full range of your dataset.

You will see a green dash line surrounding your data which indicates the range selected in the Create Table menu. You can click on the selector button to the right of the range input to adjust this range if needed.

  1. Check the My table has headers option.
  2. Press the OK button.

📝 Note: The My table has headers option needs to be checked if the first row in your dataset contains column headings. Otherwise, Excel will create a table with generic column heading titles.

Your Excel data will now be inside a table! You will immediately see that it’s inside a table as Excel will apply some default format which will make the table range very obvious.

💡 Tip: You can choose from a variety of format options for your table from the Table Design tab in the Table Styles section.

The next thing you will want to do with your table is to give it a sensible name. The table name will be used to reference the table in formulas and other tools, so giving it a short descriptive name will help you later when reading formulas.

  1. Go to the Table Design tab.
  2. Click on the Table Name input box.
  3. Type your new table name.
  4. Press the Enter key to accept the new name.

Each table in your database will need to be in a separate table, so you will need to repeat the above process for each.

How to Add New Data to Your Table

You will likely need to add new records to your database. This means you will need to add new rows to your tables.

Adding rows to an Excel table is very easy and you can do it a few different ways.

You can add new rows to your table from the right-click menu.

  1. Select a cell inside your table.
  2. Right-click on the cell.
  3. Select Insert from the menu.
  4. Select Table Rows Above from the submenu.

This will insert a new blank row directly above the selected cells in your table.

You can add a blank row to the bottom of your table with the Tab key.

  1. Place the active cell cursor in the lower right cell of the table.
  2. Press the Tab key.

A new blank row will be added to the bottom of the table.

But the easiest way to add new data to a table is to type directly below the table. Data entered directly underneath the table is automatically absorbed into the table!

Excel Workbook Layout

If you are going to create an Excel database, then you should keep it simple.

Your Excel database file should contain only the data and nothing else. This means any reports, analysis, data visualization, or other work related to the data should be done in another Excel file.

Your Excel database file should only be used for adding, editing, or deleting the data stored in the file. This will help decrease the chance of accidentally changing your data, as the only reason to open the file will be to intentionally change the data.

Each table in the database should be stored in a separate worksheet and nothing else except the table should be in that sheet. You can then name the worksheet based on the table it contains so your file is easy to navigate.

💡 Tip: Place your table starting in cell A1 and then hide the remaining columns. This way it is clear the sheet should only contain the table and nothing else.

The only other sheet you might optionally include is a table of contents to help organize the file. This is where you can list each table along with the fields it contains and a description of what these fields are.

💡 Tip: You can hyperlink the table name listed in the table of contents to its associated sheet. Select the name and press Ctrl + K to create a hyperlink. This can help you navigate the workbook when you have a lot of tables in your database.

Use Data Validation to Prevent Invalid Data

Data validation is a very important feature for any database. This allows you to ensure only specific types of data are allowed in a column.

You might create data validation rules such as.

  • Only positive whole numbers are entered in a quantity column.
  • Only certain product names are allowed in the product column.
  • A column can’t contain any duplicate values.
  • Dates are between two given dates.

Excel’s data validation tools will help you ensure the data entered in your database follow such rules.

Follow these steps to add a data validation rule to any column in your table.

  1. Left-click on the column heading to select the entire column.

When you hover the mouse cursor over the top of your column heading in a table, the cursor will change to a black downward pointing arrow. Left-click and the entire column will be selected.

The data validation will automatically propagate to any new rows added to the table.

  1. Go to the Data tab.
  2. Click on the Data Validation command.

This will open up the Data Validation menu where you will be able to choose from various validation settings. If there is no active validation in the cell, you should see the Any values option selected in the Allow criteria.

Only Allow Positive Whole Number Values

Follow these steps from the Data Validation menu to allow only positive whole number values to be entered.

  1. Go to the Settings tab in the Data Validation menu.
  2. Select the Whole number option from the Allow dropdown.
  3. Select the greater than option from the Data dropdown.
  4. Enter 0 in the Minimum input box.
  5. Press the OK button.

💡 Tip: Keep the Ignore blank option checked if you want to allow blank cells in the column.

This will apply the validation rule to the column and when a user tries to enter any number other than 1, 2, 3, etc… they will be warned the data is invalid.

Only Allow Items from a List

Selecting items from a dropdown list is a great way to avoid incorrect text input such as customer or product names.

Follow these steps from the Data Validation menu to create a dropdown list for selecting text values in a column.

  1. Go to the Settings tab in the Data Validation menu.
  2. Select the List option from the Allow dropdown.
  3. Check the In-cell dropdown option.
  4. Add the list of items to the Source input.
  5. Press the OK button.

📝 Note: If you place the list of possible options inside an Excel Table and select the full column for the Source reference, then the range reference will update as you add items to the table.

Now when you select a cell in the column you will see a dropdown list handle on the right of the cell. Click on this and you will be able to choose a value from a list.

Only Allow Unique Values

Suppose you want to ensure the list of products in your Products table is unique. You can use the Custom option in the validation settings to achieve this.

  1. Go to the Settings tab in the Data Validation menu.
  2. Select the Custom option from the Allow dropdown.
=(COUNTIFS(INDIRECT("Products[Item]"),A2)=1)
  1. Enter the above formula in the Formula input.
  2. Press the OK button.

The formula counts the number of times the current row’s value appears in the Products[Item] column using the COUNTIFS function.

It then determines if this count is equal to 1. Only values where the formula evaluates to 1 are allowed which means the product name can’t have been in the list already.

📝 Note: You need to reference the column by name using the INDIRECT function in order for the range to grow as you add items to your table!

Show Input Message when Cell is Selected

The data validation menu allows you to show a message to your users when a cell is selected. This means you can add instructions about what types of values are allowed in the column.

Follow these steps to add an input message in the Data Validation menu.

  1. Go to the Input Message tab in the Data Validation menu.
  2. Keep the Show input message when cell is selected option checked.
  3. Add some text to the Title section.
  4. Add some text to the Input message section.
  5. Press the OK button.

When you select a cell in the column which contains the data validation, a small yellow pop-up will appear with your Title and Input message text.

Prevent Invalid Data with Error Message

When you have a data validation rule in place, you will usually want to prevent invalid data from being entered.

This can be achieved using the error message feature in the Data Validation menu.

  1. Go to the Error Alert tab in the Data Validation menu.
  2. Keep the Show error alert after invalid data is entered option checked.
  3. Select the Stop option in the Style dropdown.
  4. Add some text to the Title section.
  5. Add some text to the Error message section.
  6. Press the OK button.

📝 Note: The Stop option is essential if you want to prevent the invalid data from being entered rather than only warning the user the data is invalid.

When you try to enter a repeated value in the column your custom error message will pop up and prevent the value from being entered in the cell.

Data Entry Form for Your Excel Database

Excel doesn’t have any fool-proof methods to ensure data is entered correctly, even when data validation techniques previously mentioned are used.

When a user copies and pastes or cuts and pastes values, this can override data validation in a column and cause incorrect data to enter into your database.

Using a data entry form can help to avoid data entry errors and there are a couple of different options available.

  • Use a table for data entry.
  • Use the quick access toolbar data entry form.
  • Use Microsoft Forms for data entry.
  • Use Microsoft Power Automate app for data entry.
  • Use Microsoft Power Apps for data entry.

💡 Tip: Check out this post for more details on the various data entry form options for Excel.

Tools such as Microsoft Forms, Power Automate, and Power Apps will give you more data validation, access, and security controls over your data entry compared with the basic Excel options.

Access and Security for Your Excel Database

Excel isn’t a secure option for your data.

Whatever measures you set up in your Excel file to prevent users from changing data by accident or on purpose will not be foolproof.

Whoever has access to the file will be able to create, read, update, and delete data from your database if they are determined. There are also no options to assign certain privileges to certain users within an Excel file.

However, you can manage access and security to the file from SharePoint.

💡 Tip: Check out this post from Microsoft about recommendations for securing SharePoint files for more details.

When you store your Excel file in SharePoint you’ll also be able to see recent changes.

  1. Go to the Review tab.
  2. Click on the Show Changes command.

This will open up the Changes pane on the right-hand side of the Excel sheet.

It will show you a chronological list of all the recent changes in the workbook, who made those changes, when they made the change, and what the previous value was.

You can also right-click on a cell and select Show Changes. This will open the Changes pane filtered to only show the changes for that particular cell.

This is a great way to track down the cause of any potential errors in your data.

Query Your Excel Database with Power Query

Your Excel database file should only be used to add, edit, or delete records in your tables.

So how do you use the data for anything else such as creating reports, analysis, or dashboards?

This is the magic of Power Query! It will allow you to connect to your Excel database and query the data in a read-only manner. You can build all your reports, analysis, and dashboards in a separate file which can easily be refreshed with the latest data from your Excel database file.

Here’s how to use power query to quickly import your data into any Excel file.

  1. Go to the Data tab.
  2. Click on the Get Data command.
  3. Choose the From File option.
  4. Choose the From Excel Workbook option in the submenu.

This will open a file picker menu where you can navigate to your Excel database file.

  1. Select your Excel database file.
  2. Click on the Import button.

⚠️ Warning: Make sure your Excel database file is closed or the import process will show a warning that it’s unable to connect to the file because it’s in use!

Clicking on the Import button will then open the Navigator menu. This is where you can select what data to load and where to load it.

The Navigator menu will list all the tables and sheets in the Excel file. Your tables might be listed with a suffix on the name if you’ve named the sheets and tables the same.

  1. Check the option to Select multiple items if you want to load more than one table from your database.
  2. Select which tables to load.
  3. Click on the small arrow icon next to the Load button.
  4. Select the Load To option in the Load submenu.

This will open the Import Data menu where you can choose to import your data into a Table, PivotTable, PivotChart, or only create a Connection to the data without loading it.

  1. Select the Table option.
  2. Click on the OK button.

Your data is then loaded into an Excel Table in the new workbook.

The best part is you can always get the latest data from the source database file. Go to the Data tab and press the Refresh All button to refresh the power query connection and import the latest data.

💡 Tip: You can do a lot more than just load data with Power Query. You can also transform your data in just about any imaginable way using the Transform Data button in the Navigator menu. Check out this post on how to use Power Query for more details about this amazing tool.

Analyze and Summarize Your Excel Database with Power Pivot

Power Query isn’t the only database tool Excel has. The data model and Power Pivot add-in will help you slice and dice relational data inside your Excel pivot tables.

When you load your data with Power Quer, there is an option to Add this data to the Data Model in the Import Data menu.

This option will allow you to build relationships between the various tables in your database. This way you’ll be able to analyze your orders by category even though this field doesn’t appear in the Orders table.

You can build your table relationships from the Data tab.

  1. Go to the Data tab.
  2. Click on either the Relationships or Manage Data Model command.

Now you’ll be able to analyze multiple tables from your database inside a single pivot table!

Conclusions

Data is an essential part of any business or organization. If you need to track customers, sales, inventory, or any other information then you need a database.

If you need to create a database on a budget with the tools you have available then Microsoft Excel might be the best option and is a natural fit for any tabular data because of its row and column structure.

There are many things to consider when using Excel as a database such as who will have access to the files, what type of data will be stored, and how you will use the data.

Features such as Tables, data validation, power query, and power pivot are all essential to properly storing, managing, and accessing your data.

Do you use Excel as a database? Do you have any other tips for using Excel to manage your dataset? Let me know in the comments below!

About the Author

John MacDougall

John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.

26 Sep ’22 by Antonio Nakić-Alfirević

SQL Query function in Excel

If you’re reading this article you probably know that Google Sheets has a QUERY function that allows you to run SQL-like queries against data in the sheet. This function lets you do all sorts of gymnastics with the data in your sheet, be it filtering, aggregating, or pivoting data.

Being a fully-fledged desktop app, Excel tends to be more feature-rich than Google Sheets. This is especially true in the data analytics department where Excel shines with advanced Excel functions as well as Power Query functionality.

However, Excel doesn’t natively have a QUERY function that you can use in cells on the sheet.

In this blog post, I’m going to show you how to add a QUERY function to Excel and give a few examples of how to use it.

First look

Let’s start by taking a look at the function in action.

Simple SELECT query examples

Simple SELECT query examples

The function is pretty straightforward. It accepts the SQL query as the first parameter and returns a table with the results of the query.

The results automatically spill to the necessary amount of space. This spilling behavior relies on the dynamic array functionality that’s available in Excel 365 (but isn’t in earlier versions of Microsoft Excel).

Works with Excel tables

In Google Sheets, the QUERY function references data by address (e.g. “A1:B10”) while columns are referenced by letters (e.g. A, B, C…).

This works but has some drawbacks:

  • It makes the query sensitive to the location of the data. If the data is moved or if columns are reordered, the query will break.
  • It makes the query difficult to read since it uses range addresses and column letters instead of table and column names (e.g. Employees, DateOfBirth…)
  • Adding or removing rows can break the query. For example, if the provided range is “A1:H10” the query will only take into account the first 10 rows. If additional rows are added, the query will not take them into account. You can get around this by omitting the end row number (e.g. “A1:H”), but this means that there must be no other content below the data range.

Excel, on the other hand, allows explicitly defining tables (aka ListObjects) that delineate the areas that hold data. Each Excel table has a name, as do its columns. This makes Excel tables very similar to database tables and makes them easier to work with from SQL.

Explicitly defined tables in Excel

Explicitly defined tables in Excel

Full SQL syntax support (SQLite)

Under the hood, the Windy.Query function is powered by SQLite – a small but powerful embedded database engine.

When called, the function passes the query to the built-in SQLite engine which has an adapter that lets it use Excel tables as its data source.

This means that the entire SQLite syntax is available for use in queries. In comparison, in Google Sheets, the query syntax is rather limited. It only supports a single table (no joins) and a very small set of built-in functions.

Examples of use

Since the engine under the hood is SQLite, queries can use all operations available in SQLite, including table joins, temp tables, column table expressions, window functions etc… Let’s go over some examples of how to use these in Excel.

Joining tables

Here’s an example of a simple one-to-many join:

Simple one-to-many SQL join

Simple one-to-many SQL join

The usual way of doing a simple operation such as this one in Excel would be to use xlookup or PowerQuery, but SQL is now another option. And if we needed anything more complex than a simple join, SQL would quickly shine as the most powerful and convenient option of the three.

Merging table rows (union)

Another way we might want to combine two (or more) tables is to combine their rows. We can do this with a SQL UNION operator.

The tables might have some rows in common. If we want to keep only one instance of such rows we would use the regular UNION operator. If we want to keep both versions of rows that are in common, we would use the UNION ALL operator.

Merging rows from two tables

Merging rows from two tables

Finding differences between two tables

In the previous example, we had two tables that had some rows in common and some rows not. Let’s assume, for example, that the first table contains last year’s list of employees and the second table is the new list of employees.

If we wanted to find out the differences between the two tables, we could easily do that with a bit of SQL.

All of the rows that are in the first table but not in the second one we will mark as “deleted”. All of the rows that are in the second table but not in the first one we will mark as “added”. Here’s what that SQL query looks like:

select
	id, name, 'deleted'
from
	employees e where not exists (select * from Employees_New en where e.id == en.Id)
union
select
	id, name, 'added'
from
	employees_new en where not exists (select * from Employees e where e.id == en.Id)

And here’s what the result looks like:

Calculating a diff between two tables

Calculating a diff between two tables

Ranking rows

Another useful thing we might want to do is rank rows based on some criteria. For example, suppose we have a table with a list of cities. For each city we have its population and the country it belongs to.

Our task is to find the top 3 cities in each country based on population. Here’s how we might do that in SQL.

-- we use this CTE so we can reference the calculated 'rank_pop' column in the where clause
with cte as (
	select
		city,
		country,
		population,
		-- using the RANK() window function
		RANK() OVER (PARTITION BY country ORDER BY population) as rank_pop
	from
		cities c)
select
	*
from
	cte
where
	-- filtering by the 'rank_pop' column from the CTE
	rank_pop <= 3
order by country, rank_pop

Rank cities by population in each country, return top 3 per country

Rank cities by population in each country, return top 3 for each country

This query is a bit more complex than the previous ones. It uses a common table expression and a window function (the rank function), and showcases the ability to write complex SQL in queries.

Queries can also make use of dozens of built-in SQLite functions. Various specialized extended functions such as RegexReplace, GPSDist (GPS distance between two points) and LevDist (fuzzy text matching) are also available.

Updating tables

OK, this next example is a bit of a hack, but a useful one… The query you supply doesn’t need to be a SELECT query. You can do UPDATE/INSERT/DELETE statements as well, and these will modify the data in the target Excel tables.

Updating Excel tables with SQL

Updating workbook tables with SQL

This can be a handy way to clean and transform data in your tables in place, without having to export/import the data to an external database (e.g. SQL Server, MySql, Postgres…).

This works because the SQLite engine isn’t copying the data. Rather, it’s using an adapter that lets it access live data in the Excel table.

How does the function see Excel tables?

At first glance, it might seem strange that the query can access your workbook tables. After all, we did not pass them in as parameters, and functions normally only work with parameters that are passed to them.

However, the Windy.Query function is aware of the workbook it’s being called from and it can read data from the workbook’s tables without the need for passing them in as parameters. This makes the function much easier to call especially when working with multiple tables.

Column Headers

Results returned by the Windy.Query function can optionally include headers. This is controlled by the second parameter of the function.

Toggling column headers on/off

Toggling column headers on/off

The texts in the column headers are determined by the SQL query itself. You can easily rename result columns by aliasing them in the select list.

Aliasing column headers

Aliasing column headers

Automatically refresh results

By default, the SQL query runs as a one-off operation when you enter the formula but does not refresh if the source tables change. However, if you want the query to refresh whenever one of the source tables changes, you can easily do so by setting the autoRefresh argument to true.

Automatic refresh of results when source data changes

Automatic refresh of results when source data changes

Note that the auto-refresh functionality relies on Excel’s RTD (Real-Time Data) server. The RTD server usually throttles updates so functions don’t overwhelm Excel with frequent updates. The default throttle interval is 2s meaning that the function will not update more than once every 2s. To improve responsiveness, you can lower this value to something like 20ms. The simplest way to do this is through the “Configure” dialog in the QueryStorm runtime’s ribbon.

Adjusting the RTD interval in Excel

Adjusting the RTD interval in Excel

Passing parameters

When needed, SQL queries can use values from cells as parameters. To use a cell as a parameter in a query, start by giving the cell a name (named range).

Give the parameter cell a name

Give the parameter cell a name

Once the cell has a name, you can reference it in the query using the @paramName or $paramName syntax.

Use the parameter in the SQL query

Use the parameter in the SQL query

If automatic refresh is turned on, results will automatically refresh whenever one of the parameter cells changes its value.

Automatic refresh of results when parameter cell changes

Automatic refresh of results when parameter cell changes

Performance

This is all well and good for small tables, you might think, but how does it handle large data sets? Well, it handles them quite well. The function can read source tables of 100k rows and 10 columns within a few milliseconds and can return this amount of data in a second or two. In addition to this, all columns are automatically indexed so searches and joins are extremely performant as well.

This makes the function perform very well, both from the data throughput standpoint as well as from the computational one.

OK, so is this better than the Google Sheets version of the QUERY function?

Yes, dah. Did you read the previous chapters? 😛

Installing the Windy.Query function

So how do you install this function into your Excel? It’s a simple 2-step process.

Step 1 is to install the QueryStorm Runtime add-in (if you don’t already have it). This is a free, 4MB add-in for Excel that lets you install and use various extensions for Excel. It’s basically an app store for Excel.

Step 2 is to click the “Extensions” button in the “QueryStorm” tab in the Excel ribbon, find the Windy.Query package in the “Online” tab, and install it.

What happens if I share the workbook with a user who doesn’t have the function?

Nothing bad. If the other user doesn’t have the function installed, they will see the last results of the query that were returned on your machine. They just won’t be able to refresh the results.

Advanced SQL query editor

Writing SQL queries in the formula bar can get a bit unwieldy. To make queries easier to write, it’s better to use a proper editor, preferably one that offers syntax highlighting and code completion for SQL and knows about the tables in your workbook.

For this purpose, I recommend using the QueryStorm IDE. This is an advanced IDE that lets you use SQL in Excel. You can write the query in the QueryStorm code editor and then paste the query into the Windy.Query function when you’re happy with it (if needed).

Using the QueryStorm IDE to write SQL queries in Excel

Using the QueryStorm IDE to write SQL queries in Excel

The IDE does more than just allow using SQL in Excel. You can use it to create and share functions and addins for Excel. In fact the QueryStorm IDE was used to create the Windy.Query function itself.

The IDE has a free community version for individuals and small companies, while users in larger companies can make use of the free trial license. For paid licenses, check out the pricing page.

You can read more in this blog post that’s dedicated to the QueryStorm SQL IDE.

Video demonstration

For a video demonstration of the Windy.Query function, take a look the following video:

Представьте себе ситуацию, Вы получили целевую выборку из одной базы данных, но для полноты картины, как всегда, нужны дополнительные данные. Проблема может быть в том, что нужная информация хранится в другой базе данных и возможности создать на ней свою таблицу нет, подключиться используя link тоже нельзя, да и количество элементов, по которым нужно получить данные, несколько больше, чем допустимое на данном источнике. Вот и получается, что возможность написать SQL запрос и получить нужные данные есть, но написать придется не один запрос, а потом потратить время на объединение полученных данных.

Выйти из подобной ситуации поможет Excel.

Уверен, что ни для кого не секрет, что MS Excel имеет встроенный модуль VBA и надстройки, позволяющие подключаться к внешним источникам данных, то есть по сути является мощным инструментом для аналитики, а значит идеально подходит для решения подобных задач.

Для того чтобы обойти проблему, нам потребуется таблица с целевой выборкой, в которой содержатся идентификаторы, по которым можно достаточно корректно получить недостающую информацию (это может быть уникальный идентификатор, назовем его ID, или набор из данных, находящихся в разных столбцах), ПК с установленным MS Excel, и доступом к БД с недостающей информацией и, конечно, желание получить ту самую информацию.

Создаем в MS Excel книгу, на листе которой размещаем таблицу с идентификаторами, по которым будем в дальнейшем формировать запрос (если у нас есть уникальный идентификатор, для обеспечения максимальной скорости обработки таблицу лучше представить в виде одного столбца), сохраняем книгу в формате *.xlsm, после чего приступаем к созданию макроса.

Через меню «Разработчик» открываем встроенный VBA редактор и начинаем творить.

Sub job_sql() — Пусть наш макрос называется job_sql.

Пропишем переменные для подключения к БД, записи данных и запроса:

Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sql As String

Опишем параметры подключения:

sql = «Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=Storoge.company.ru Storoge.»

Объявим процедуру свойства, для присвоения значения:

Set cn = New ADODB.Connection
cn.Provider = » SQLOLEDB.1″
cn.ConnectionString = sql
cn.ConnectionTimeout = 0
cn.Open

Вот теперь можно приступать непосредственно к делу.

Организуем цикл:

For i = 2 To 1000

Как вы уже поняли конечное значение i=1000 здесь только для примера, а в реальности конечное значение соответствует количеству строк в Вашей таблице. В целях унификации можно использовать автоматический способ подсчета количества строк, например, вот такую конструкцию:

Dim LastRow As Long
LastRow = ActiveSheet.UsedRange.Row — 1 + ActiveSheet.UsedRange.Rows.Count

Тогда открытие цикла будет выглядеть так:

For i = 2 To LastRow

Как я уже говорил выше MS Excel является мощным инструментом для аналитики, и возможности Excel VBA не заканчиваются на простом переборе значений или комбинаций значений. При наличии известных Вам закономерностей можно ограничить объем выгружаемой из БД информации путем добавления в макрос простых условий, например:

If Cells(i, 2) = «Ваше условие» Then

Итак, мы определились с объемом и условиями выборки, организовали подключение к БД и готовы формировать запрос. Предположим, что нам нужно получить информацию о размере ежемесячного платежа [Ежемесячный платеж] из таблицы [payments].[refinans_credit], но только по тем случаям, когда размер ежемесячного платежа больше 0

sql = «select [Ежемесячный платеж] from [PAYMENTS].[refinans_credit] » & _
«where [Ежемесячный платеж]>0 and [Номер заявки] ='» & Cells(i, 1) & «‘ «

Если значений для формирования запроса несколько, соответственно прописываем их в запросе:

«where [Ежемесячный платеж]>0 and [Номер заявки] = ‘» & Cells(i, 1) & «‘ » & _
» and [Дата платежа]='» & Cells(i, 2) & «‘»

В целях самоконтроля я обычно записываю сформированный макросом запрос, чтобы иметь возможность проверить его корректность и работоспособность, для этого добавим вот такую строчку:

Cells(i, 3) = sql

в третьем столбце записываются запросы.

Выполняем SQL запрос:

Set rs = cn.Execute(sql)

А чтобы хоть как-то наблюдать за выполнением макроса выведем изменение i в статус-бар

Application.StatusBar = «Execute script …» & i
Application.ScreenUpdating = False

Теперь нам нужно записать полученные результаты. Для этого будем использовать оператор Do While:

j = 0
Do While Not rs.EOF
For ii = 0 To rs.Fields.Count — 1
Cells(i, 4 + j + ii) = rs.Fields(0 + ii) ‘& «;»

Указываем ячейки для вставки полученных данных (4 в примере это номер столбца с которого начинаем запись результатов)

Next ii
j = j + rs.Fields.Count
s.MoveNext
Loop
rs.Close
End If

— закрываем цикл If, если вводили дополнительные условия

Next i
cn.Close
Application.StatusBar = «Готово»
End Sub

— закрываем макрос.

В дополнение хочу отметить, что данный макрос позволяет обращаться как к БД на MS SQL так и к БД Oracle, разница будет только в параметрах подключения и собственно в синтаксисе SQL запроса.

В приведенном примере для авторизации при подключении к БД используется доменная аутентификация.

А как быть если для аутентификации необходимо ввести логин и пароль? Ничего невозможного нет. Изменим часть макроса, которая отвечает за подключение к БД следующим образом:

sql = «Provider= SQLOLEDB.1;Password=********;User ID=********;Data Source= Storoge.company.ru Storoge;APP=SFM»

Но в этом случае при использовании макроса возникает риск компрометации Ваших учетных данных. Поэтому лучше программно удалять учетные данные после выполнения макроса. Разместим поля для ввода пароля и логина на листе и изменим макрос следующим образом:

sql = «Provider= SQLOLEDB.1;Password=» & Sheets(«Лист аутентификации»).TextBox1.Value & «;User ID=» & Sheets(«Лист аутентификации «).TextBox2.Value & «;Data Source= Storoge.company.ru Storoge;APP=SFM»

Место для расположения текстовых полей не принципиально, можно расположить их на листе с таблицей в первых строках, но мне удобней размещать поля на отдельном листе. Чтобы введенные учетные данные не сохранялись вместе с результатом выполнения макроса в конце исполняемого кода дописываем:

Sheets(«Выгрузка»).TextBox1.Value = «« Sheets(»Выгрузка«).TextBox2.Value = »»

То есть просто присваиваем текстовым полям пустые значения, таким образом после выполнения макроса поля для ввода пароля и логина окажутся пустыми.

Вот такое вполне жизнеспособное решение, позволяющее сократить трудозатраты при получении и обработке данных, я использую. Надеюсь мой опыт применения SQL запросов в Excel будет полезен и вам в решении текущих задач.

Содержание

  • Создание SQL запроса в Excel
    • Способ 1: использование надстройки
    • Способ 2: использование встроенных инструментов Excel
    • Способ 3: подключение к серверу SQL Server
  • Вопросы и ответы

SQL в Microsoft Excel

SQL – популярный язык программирования, который применяется при работе с базами данных (БД). Хотя для операций с базами данных в пакете Microsoft Office имеется отдельное приложение — Access, но программа Excel тоже может работать с БД, делая SQL запросы. Давайте узнаем, как различными способами можно сформировать подобный запрос.

Читайте также: Как создать базу данных в Экселе

Язык запросов SQL отличается от аналогов тем, что с ним работают практически все современные системы управления БД. Поэтому вовсе не удивительно, что такой продвинутый табличный процессор, как Эксель, обладающий многими дополнительными функциями, тоже умеет работать с этим языком. Пользователи, владеющие языком SQL, используя Excel, могут упорядочить множество различных разрозненных табличных данных.

Способ 1: использование надстройки

Но для начала давайте рассмотрим вариант, когда из Экселя можно создать SQL запрос не с помощью стандартного инструментария, а воспользовавшись сторонней надстройкой. Одной из лучших надстроек, выполняющих эту задачу, является комплекс инструментов XLTools, который кроме указанной возможности, предоставляет массу других функций. Правда, нужно заметить, что бесплатный период пользования инструментом составляет всего 14 дней, а потом придется покупать лицензию.

Скачать надстройку XLTools

  1. После того, как вы скачали файл надстройки xltools.exe, следует приступить к его установке. Для запуска инсталлятора нужно произвести двойной щелчок левой кнопки мыши по установочному файлу. После этого запустится окно, в котором нужно будет подтвердить согласие с лицензионным соглашением на использование продукции компании Microsoft — NET Framework 4. Для этого всего лишь нужно кликнуть по кнопке «Принимаю» внизу окошка.
  2. Принятие лицензиного соглашение на использование компонента Microsoft NET Framework 4

  3. После этого установщик производит загрузку обязательных файлов и начинает процесс их установки.
  4. Загрузка обязательных файлов

  5. Далее откроется окно, в котором вы должны подтвердить свое согласие на установку этой надстройки. Для этого нужно щелкнуть по кнопке «Установить».
  6. Окно подтверждения согласия на установку надстройки

  7. Затем начинается процедура установки непосредственно самой надстройки.
  8. Установка надстройки

  9. После её завершения откроется окно, в котором будет сообщаться, что инсталляция успешно выполнена. В указанном окне достаточно нажать на кнопку «Закрыть».
  10. Закрытие окна установщика надстройки

  11. Надстройка установлена и теперь можно запускать файл Excel, в котором нужно организовать SQL запрос. Вместе с листом Эксель открывается окно для ввода кода лицензии XLTools. Если у вас имеется код, то нужно ввести его в соответствующее поле и нажать на кнопку «OK». Если вы желаете использовать бесплатную версию на 14 дней, то следует просто нажать на кнопку «Пробная лицензия».
  12. Окно лицензии надстройки XLTools

  13. При выборе пробной лицензии открывается ещё одно небольшое окошко, где нужно указать своё имя и фамилию (можно псевдоним) и электронную почту. После этого жмите на кнопку «Начать пробный период».
  14. Окно активации пробного периода надстройки XLTools

  15. Далее мы возвращаемся к окну лицензии. Как видим, введенные вами значения уже отображаются. Теперь нужно просто нажать на кнопку «OK».
  16. Активация пробной лицензии надстройки XLTools

  17. После того, как вы проделаете вышеуказанные манипуляции, в вашем экземпляре Эксель появится новая вкладка – «XLTools». Но не спешим переходить в неё. Прежде, чем создавать запрос, нужно преобразовать табличный массив, с которым мы будем работать, в так называемую, «умную» таблицу и присвоить ей имя.
    Для этого выделяем указанный массив или любой его элемент. Находясь во вкладке «Главная» щелкаем по значку «Форматировать как таблицу». Он размещен на ленте в блоке инструментов «Стили». После этого открывается список выбора различных стилей. Выбираем тот стиль, который вы считаете нужным. На функциональность таблицы указанный выбор никак не повлияет, так что основывайте свой выбор исключительно на основе предпочтений визуального отображения.
  18. Переход к созданию умной таблицы в Microsoft Excel

    Lumpics.ru

  19. Вслед за этим запускается небольшое окошко. В нем указываются координаты таблицы. Как правило, программа сама «подхватывает» полный адрес массива, даже если вы выделили только одну ячейку в нем. Но на всякий случай не мешает проверить ту информацию, которая находится в поле «Укажите расположение данных таблицы». Также нужно обратить внимание, чтобы около пункта «Таблица с заголовками», стояла галочка, если заголовки в вашем массиве действительно присутствуют. Затем жмите на кнопку «OK».
  20. Окно форматирования таблицы в Microsoft Excel

  21. После этого весь указанный диапазон будет отформатирован, как таблица, что повлияет как на его свойства (например, растягивание), так и на визуальное отображение. Указанной таблице будет присвоено имя. Чтобы его узнать и по желанию изменить, клацаем по любому элементу массива. На ленте появляется дополнительная группа вкладок – «Работа с таблицами». Перемещаемся во вкладку «Конструктор», размещенную в ней. На ленте в блоке инструментов «Свойства» в поле «Имя таблицы» будет указано наименование массива, которое ему присвоила программа автоматически.
  22. Наименование таблицы по умолчанию в Microsoft Excel

  23. При желании это наименование пользователь может изменить на более информативное, просто вписав в поле с клавиатуры желаемый вариант и нажав на клавишу Enter.
  24. Измененное наименование таблицы в Microsoft Excel

  25. После этого таблица готова и можно переходить непосредственно к организации запроса. Перемещаемся во вкладку «XLTools».
  26. Переход во вкладку XLTools в Microsoft Excel

  27. После перехода на ленте в блоке инструментов «SQL запросы» щелкаем по значку «Выполнить SQL».
  28. Переход в окно выполнения SQL надстройки XLTools в программе Microsoft Excel

  29. Запускается окно выполнения SQL запроса. В левой его области следует указать лист документа и таблицу на древе данных, к которой будет формироваться запрос.

    В правой области окна, которая занимает его большую часть, располагается сам редактор SQL запросов. В нем нужно писать программный код. Наименования столбцов выбранной таблицы там уже будут отображаться автоматически. Выбор столбцов для обработки производится с помощью команды SELECT. Нужно оставить в перечне только те колонки, которые вы желаете, чтобы указанная команда обрабатывала.

    Далее пишется текст команды, которую вы хотите применить к выбранным объектам. Команды составляются при помощи специальных операторов. Вот основные операторы SQL:

    • ORDER BY – сортировка значений;
    • JOIN – объединение таблиц;
    • GROUP BY – группировка значений;
    • SUM – суммирование значений;
    • DISTINCT – удаление дубликатов.

    Кроме того, в построении запроса можно использовать операторы MAX, MIN, AVG, COUNT, LEFT и др.

    В нижней части окна следует указать, куда именно будет выводиться результат обработки. Это может быть новый лист книги (по умолчанию) или определенный диапазон на текущем листе. В последнем случае нужно переставить переключатель в соответствующую позицию и указать координаты этого диапазона.

    После того, как запрос составлен и соответствующие настройки произведены, жмем на кнопку «Выполнить» в нижней части окна. После этого введенная операция будет произведена.

Окно выполнения SQL запроса надстройкой XLTools в Microsoft Excel

Урок: «Умные» таблицы в Экселе

Способ 2: использование встроенных инструментов Excel

Существует также способ создать SQL запрос к выбранному источнику данных с помощью встроенных инструментов Эксель.

  1. Запускаем программу Excel. После этого перемещаемся во вкладку «Данные».
  2. Переход во вкладку Данные в Microsoft Excel

  3. В блоке инструментов «Получение внешних данных», который расположен на ленте, жмем на значок «Из других источников». Открывается список дальнейших вариантов действий. Выбираем в нем пункт «Из мастера подключения данных».
  4. Переход в Мастер подключения данных в Microsoft Excel

  5. Запускается Мастер подключения данных. В перечне типов источников данных выбираем «ODBC DSN». После этого щелкаем по кнопке «Далее».
  6. Окно Мастера подключения данных в Microsoft Excel

  7. Открывается окно Мастера подключения данных, в котором нужно выбрать тип источника. Выбираем наименование «MS Access Database». Затем щелкаем по кнопке «Далее».
  8. Окно выбора типа источника Мастера подключения данных в Microsoft Excel

  9. Открывается небольшое окошко навигации, в котором следует перейти в директорию расположения базы данных в формате mdb или accdb и выбрать нужный файл БД. Навигация между логическими дисками при этом производится в специальном поле «Диски». Между каталогами производится переход в центральной области окна под названием «Каталоги». В левой области окна отображаются файлы, расположенные в текущем каталоге, если они имеют расширение mdb или accdb. Именно в этой области нужно выбрать наименование файла, после чего кликнуть на кнопку «OK».
  10. Окно выбора базы данных в Microsoft Excel

  11. Вслед за этим запускается окно выбора таблицы в указанной базе данных. В центральной области следует выбрать наименование нужной таблицы (если их несколько), а потом нажать на кнопку «Далее».
  12. Окно выбора таблицы базы данных в Microsoft Excel

  13. После этого открывается окно сохранения файла подключения данных. Тут указаны основные сведения о подключении, которое мы настроили. В данном окне достаточно нажать на кнопку «Готово».
  14. Окно сохранения файла подключения данных в Microsoft Excel

  15. На листе Excel запускается окошко импорта данных. В нем можно указать, в каком именно виде вы хотите, чтобы данные были представлены:
    • Таблица;
    • Отчёт сводной таблицы;
    • Сводная диаграмма.

    Выбираем нужный вариант. Чуть ниже требуется указать, куда именно следует поместить данные: на новый лист или на текущем листе. В последнем случае предоставляется также возможность выбора координат размещения. По умолчанию данные размещаются на текущем листе. Левый верхний угол импортируемого объекта размещается в ячейке A1.

    После того, как все настройки импорта указаны, жмем на кнопку «OK».

  16. Окно импорта данных в Microsoft Excel

  17. Как видим, таблица из базы данных перемещена на лист. Затем перемещаемся во вкладку «Данные» и щелкаем по кнопке «Подключения», которая размещена на ленте в блоке инструментов с одноименным названием.
  18. Переход в окно подключений в Microsoft Excel

  19. После этого запускается окно подключения к книге. В нем мы видим наименование ранее подключенной нами базы данных. Если подключенных БД несколько, то выбираем нужную и выделяем её. После этого щелкаем по кнопке «Свойства…» в правой части окна.
  20. Переход в свойства базы данных в Microsoft Excel

  21. Запускается окно свойств подключения. Перемещаемся в нем во вкладку «Определение». В поле «Текст команды», находящееся внизу текущего окна, записываем SQL команду в соответствии с синтаксисом данного языка, о котором мы вкратце говорили при рассмотрении Способа 1. Затем жмем на кнопку «OK».
  22. Окно свойств подключения в Microsoft Excel

  23. После этого производится автоматический возврат к окну подключения к книге. Нам остается только кликнуть по кнопке «Обновить» в нем. Происходит обращение к базе данных с запросом, после чего БД возвращает результаты его обработки назад на лист Excel, в ранее перенесенную нами таблицу.

Отправка запроса к базе данных в окне подключения к книге в Microsoft Excel

Способ 3: подключение к серверу SQL Server

Кроме того, посредством инструментов Excel существует возможность соединения с сервером SQL Server и посыла к нему запросов. Построение запроса не отличается от предыдущего варианта, но прежде всего, нужно установить само подключение. Посмотрим, как это сделать.

  1. Запускаем программу Excel и переходим во вкладку «Данные». После этого щелкаем по кнопке «Из других источников», которая размещается на ленте в блоке инструментов «Получение внешних данных». На этот раз из раскрывшегося списка выбираем вариант «С сервера SQL Server».
  2. Переход к окну подключения к серверу SQL Server в Microsoft Excel

  3. Происходит открытие окна подключения к серверу баз данных. В поле «Имя сервера» указываем наименование того сервера, к которому выполняем подключение. В группе параметров «Учетные сведения» нужно определиться, как именно будет происходить подключение: с использованием проверки подлинности Windows или путем введения имени пользователя и пароля. Выставляем переключатель согласно принятому решению. Если вы выбрали второй вариант, то кроме того в соответствующие поля придется ввести имя пользователя и пароль. После того, как все настройки проведены, жмем на кнопку «Далее». После выполнения этого действия происходит подключение к указанному серверу. Дальнейшие действия по организации запроса к базе данных аналогичны тем, которые мы описывали в предыдущем способе.

Окно Мастера подключения данных в программе Microsoft Excel

Как видим, в Экселе SQL запрос можно организовать, как встроенными инструментами программы, так и при помощи сторонних надстроек. Каждый пользователь может выбрать тот вариант, который удобнее для него и является более подходящим для решения конкретно поставленной задачи. Хотя, возможности надстройки XLTools, в целом, все-таки несколько более продвинутые, чем у встроенных инструментов Excel. Главный же недостаток XLTools заключается в том, что срок бесплатного пользования надстройкой ограничен всего двумя календарными неделями.

Еще статьи по данной теме:

Помогла ли Вам статья?

You must have used MS Excel for tasks like preparing reports, forecasts, and budgets. But do you know Excel is much powerful than this.  As, in Excel you can make a searchable database.

Want to learn how to create searchable database in Excel? don’t worry this post will guide you to make a database in Excel.

Well if we talk about Excel database capabilities than no doubt it is very powerful. Besides of creating simple searchable database in Excel you can also it for making relational database in Excel.

So, let’s take a complete overview on how to create database in Excel whether it’s searchable or relational?

What’s The Need Or Benefits Of Making Database In Excel?

Excel Spreadsheets are mainly designed for evaluating the data and sort listing the items, for short term storage of raw data. Overall, spreadsheet is used for crunching numbers and for storing single list of items. So, it is the best application for keeping inventory, computing data and statistical data modeling.

But when it comes to store large amount of data it’s best to use a database in Excel. Database suits best for circumstances where more than two user needs to share their information.

Apart from this, the two most important benefits of database in Excel are:

  • Reduced data redundancy
  • It will raise the capacity of data integrity
  • Reduced updating errors and increased consistency
  • Greater data integrity and independence from applications programs
  • You can easily maintain report and share your data
  • Improved data security
  • Reduced data entry, storage, and retrieval costs

Just follow down the steps mentioned below to create a searchable database Excel.

Step 1: Entering the data

In a database, columns are called as fields. So, as per your need you can add as many fields you need.

In the shown example, database fields are StdID, StdName, State, Age, Department, and Class Teacher.

database-creation-steps-in-excel-image-1

Now you can enter data into this newly creating database easily. Each time you enter a new data it will get fill-up in the first empty row after the Fields.

Like this,

database-creation-steps-in-excel-image-2

So, you can also see how easy it is to enter data into an Excel database.

Step 2: Entering Data Correctly

While entering data into the Excel database, don’t leave any row or column empty. As it is strictly prohibited.

database-creation-steps-in-excel-image-3

database-creation-steps-in-excel-image-4

It’s a clear breakdown of your Excel database. actually, the reason behind this is. As soon as Excel finds a completely blank column/row. It doesn’t count that column or row in the database.

So, if you left any row or column in your database completely empty then it will divide your database into different parts. Whatever functions you apply to your database will not work for that disconnected piece of information.

Although it is allowed to leave some cells of row to be empty. Like this:

database-creation-steps-in-excel-image-5

Step 3: Know that the Rows are called Records

Each single row of database is known as records. so, you can see here all the rows are records.

database-creation-steps-in-excel-image-6

Step 4: Know that the Columns are called Fields

All the headings of the database columns are termed as Field Names.

So here in the shown figure, database field name are: StdIDStdNameStateAgeDepartment, and Class Teacher.

database-creation-steps-in-excel-image-7

Note:

Try to format field names other than the rows of the database. Table field names are organized with different styles other than table’s cell.

Step 5: Creating the Table

For making table in your database, just choose for any cell in the data range. After then in the insert tab make a click on the table command.

database-creation-steps-in-excel-image-8

Clicking on the table will open a Create Table dialog box. Tap to the ok option and it create a table.

database-creation-steps-in-excel-image-9

For filtering out the data, make use of the drop-down arrows which is appearing on the heading of each column.

Step 6: Using the Database Tools

Well for the proper data analysis and interpretation in excel database you can make use of database tools. For learning more about such tools click here.

Step 7: Expanding the Database

Now everything set up, so you can start adding more records and fields in your database.

Step 8: Completing the Database Formatting

At last you just have do formatting of the database columns. There are many tools to do cells formatting in the database. Like you can make use of the cell styles, within the drop down “Format As Table”. You can also work with the commands present in the format cells dialog box.

That’s all, you have created a searchable database in your Excel spreadsheet.  Now it’s time to learn how to use this Searchable Database In Excel.

How To Use A Searchable Database In Excel?

How To Use A Searchable Database In Excel

Use Excel’s Lookup functions to search a database

by using the Excel Lookup functions, one can easily design a worksheet which enable you to search any database table.

Suppose, you have imported following table from your Access database into sheet 2 of the Excel workbook.

Use A Searchable Database In Excel

To make an Excel worksheet which can be used to check intern’s pay scale just by providing intern’s ID. Here are the following steps to perform:

  1. Open your Excel workbook, tap on the Sheet2 tab, and choose the range A2:H5.
  2. Now hit on the Name box and type Interndata. After then press [Enter].
  3. Tap on the Sheet1 tab.
  4. Select the cell D6 and put Employee ID.
  5. Choose the cell D8 and assign Name.
  6. Select the cell E8 and put the following function:

=VLOOKUP(E6,Interndata,3,FALSE)&” “&VLOOKUP(E6,Interndata,2,FALSE)

  1. In the D10 enter the Pay Rate.
  2. Now tap to the E10 and enter the following function:

=VLOOKUP(E6,Interndata,8,FALSE)

  1. It’s time to change the cell format of E6, E8, and E10 for matching the data type with the data present in table.
  2. Now add a header and do formatting as done and shown here.

Use A Searchable Database In Excel 1

How Does A Relational Database Work In Excel?

How Does A Relational Database Work In Excel

Excel is designed in such a way that it can smoothly work with the database. When the database items are associated, they make a record within multiple records’ group. Each Single record could be equivalent of row in spreadsheet. The hard to ignore the connection.

For creating a relational database in Excel, you have to join a master spreadsheet with slave spreadsheet or tables.

So, all an all, a relational database is having a master table which links with its slave tables, that are named as child tables.

Wrap up:

So, now you know it’s not that difficult task to make a searchable database in Excel. by performing the above steps, you can easily make a functional database which can be used for adding records. It can also be used to search for specific values in existing records by making use of the filter function.

Well this Excel database works smoothly for numbers of records. But the application performance starts degrading down after the accumulation of thousand of records.

Priyanka is an entrepreneur & content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.

Понравилась статья? Поделить с друзьями:
  • Worksheet object in word
  • Working with data validation in excel
  • Working with columns in word
  • Working well with others word
  • Working out word meaning from context