Note: Microsoft Access doesn’t support importing Excel data with an applied sensitivity label. As a workaround, you can remove the label before importing and then re-apply the label after importing. For more information, see Apply sensitivity labels to your files and email in Office.
This article shows you how to move your data from Excel to Access and convert your data to relational tables so that you can use Microsoft Excel and Access together. To summarize, Access is best for capturing, storing, querying, and sharing data, and Excel is best for calculating, analyzing, and visualizing data.
Two articles, Using Access or Excel to manage your data and Top 10 reasons to use Access with Excel, discuss which program is best suited for a particular task and how to use Excel and Access together to create a practical solution.
When you move data from Excel to Access, there are three basic steps to the process.
Note: For information on data modeling and relationships in Access, see Database design basics.
Step 1: Import data from Excel to Access
Importing data is an operation that can go a lot more smoothly if you take some time to prepare and clean your data. Importing data is like moving to a new home. If you clean out and organize your possessions before you move, settling into your new home is much easier.
Clean your data before you import
Before you import data into Access, in Excel it’s a good idea to:
-
Convert cells that contain non-atomic data (that is, multiple values in one cell) to multiple columns. For example, a cell in a «Skills» column that contains multiple skill values, such as «C# programming,» «VBA programming,» and «Web design» should be broken out to separate columns that each contain only one skill value.
-
Use the TRIM command to remove leading, trailing, and multiple embedded spaces.
-
Remove non-printing characters.
-
Find and fix spelling and punctuation errors.
-
Remove duplicate rows or duplicate fields.
-
Ensure that columns of data do not contain mixed formats, especially numbers formatted as text or dates formatted as numbers.
For more information, see the following Excel help topics:
-
Top ten ways to clean your data
-
Filter for unique values or remove duplicate values
-
Convert numbers stored as text to numbers
-
Convert dates stored as text to dates
Note: If your data cleaning needs are complex, or you don’t have the time or resources to automate the process on your own, you might consider using a third-party vendor. For more information, search for «data cleansing software» or «data quality» by your favorite search engine in your Web browser.
Choose the best data type when you import
During the import operation in Access, you want to make good choices so that you receive few (if any) conversion errors that will require manual intervention. The following table summarizes how Excel number formats and Access data types are converted when you import data from Excel to Access, and offers some tips on the best data types to choose in the Import Spreadsheet Wizard.
Excel number format |
Access data type |
Comments |
Best practice |
---|---|---|---|
Text |
Text, Memo |
The Access Text data type stores alphanumeric data up to 255 characters. The Access Memo data type stores alphanumeric data up to 65,535 characters. |
Choose Memo to avoid truncating any data. |
Number, Percentage, Fraction, Scientific |
Number |
Access has one Number data type that varies based on a Field Size property (Byte, Integer, Long Integer, Single, Double, Decimal). |
Choose Double to avoid any data conversion errors. |
Date |
Date |
Access and Excel both use the same serial date number to store dates. In Access, the date range is larger: from -657,434 (January 1, 100 A.D.) to 2,958,465 (December 31, 9999 A.D.). Because Access does not recognize the 1904 date system (used in Excel for the Macintosh), you need to convert the dates either in Excel or Access to avoid confusion. For more information, see Change the date system, format, or two-digit year interpretation and Import or link to data in an Excel workbook. |
Choose Date. |
Time |
Time |
Access and Excel both store time values by using the same data type. |
Choose Time, which is usually the default. |
Currency, Accounting |
Currency |
In Access, the Currency data type stores data as 8-byte numbers with precision to four decimal places, and is used to store financial data and prevent rounding of values. |
Choose Currency, which is usually the default. |
Boolean |
Yes/No |
Access uses -1 for all Yes values and 0 for all No values, whereas Excel uses 1 for all TRUE values and 0 for all FALSE values. |
Choose Yes/No, which automatically converts underlying values. |
Hyperlink |
Hyperlink |
A hyperlink in Excel and Access contains a URL or Web address that you can click and follow. |
Choose Hyperlink, otherwise Access may use the Text data type by default. |
Once the data is in Access, you can delete the Excel data. Don’t forget to backup the original Excel workbook first before deleting it.
For more information, see the Access help topic Import or link to data in an Excel workbook.
Automatically append data the easy way
A common problem Excel users have is appending data with the same columns into one large worksheet. For example, you may have an asset tracking solution that started out in Excel but now has grown to include files from many workgroups and departments. This data may be in different worksheets and workbooks, or in text files that are data feeds from other systems. There is no user interface command or easy way to append similar data in Excel.
The best solution is to use Access, where you can easily import and append data into one table by using the Import Spreadsheet Wizard. Furthermore, you can append a lot of data into one table. You can save the import operations, add them as scheduled Microsoft Outlook tasks, and even use macros to automate the process.
Step 2: Normalize data by using the Table Analyzer Wizard
At first glance, stepping through the process of normalizing your data may seem a daunting task. Fortunately, normalizing tables in Access is a process that is much easier, thanks to the Table Analyzer Wizard.
1. Drag selected columns to a new table and automatically create relationships
2. Use button commands to rename a table, add a primary key, make an existing column a primary key, and undo the last action
You can use this wizard to do the following:
-
Convert a table into a set of smaller tables and automatically create a primary and foreign key relationship between the tables.
-
Add a primary key to an existing field that contains unique values, or create a new ID field that uses the AutoNumber data type.
-
Automatically create relationships to enforce referential integrity with cascading updates. Cascading deletes are not automatically added to prevent accidentally deleting data, but you can easily add cascading deletes later.
-
Search new tables for redundant or duplicate data (such as the same customer with two different phone numbers) and update this as desired.
-
Back up the original table and rename it by appending «_OLD» to its name. Then, you create a query that reconstructs the original table, with the original table name so that any existing forms or reports based on the original table will work with the new table structure.
For more information, see Normalize your data using the Table Analyzer.
Step 3: Connect to Access data from Excel
After the data has been normalized in Access and a query or table has been created that reconstructs the original data, it’s a simple matter of connecting to the Access data from Excel. Your data is now in Access as an external data source, and so can be connected to the workbook through a data connection, which is a container of information that is used to locate, log on to, and access the external data source. Connection information is stored in the workbook and can also be stored in a connection file, such as an Office Data Connection (ODC) file (.odc file name extension) or a Data Source Name file (.dsn extension). After you connect to external data, you can also automatically refresh (or update) your Excel workbook from Access whenever the data is updated in Access.
For more information, see Import data from external data sources (Power Query).
Get your data into Access
This section walks you through the following phases of normalizing your data: Breaking values in the Salesperson and Address columns into their most atomic pieces, separating related subjects into their own tables, copying and pasting those tables from Excel into Access, creating key relationships between the newly created Access tables, and creating and running a simple query in Access to return information.
Example data in non-normalized form
The following worksheet contains non-atomic values in the Salesperson column and the Address column. Both columns should be split into two or more separate columns. This worksheet also contains information about salespersons, products, customers, and orders. This information should also be split further, by subject, into separate tables.
Salesperson |
Order ID |
Order Date |
Product ID |
Qty |
Price |
Customer Name |
Address |
Phone |
---|---|---|---|---|---|---|---|---|
Li, Yale |
2349 |
3/4/09 |
C-789 |
3 |
$7.00 |
Fourth Coffee |
7007 Cornell St Redmond, WA 98199 |
425-555-0201 |
Li, Yale |
2349 |
3/4/09 |
C-795 |
6 |
$9.75 |
Fourth Coffee |
7007 Cornell St Redmond, WA 98199 |
425-555-0201 |
Adams, Ellen |
2350 |
3/4/09 |
A-2275 |
2 |
$16.75 |
Adventure Works |
1025 Columbia Circle Kirkland, WA 98234 |
425-555-0185 |
Adams, Ellen |
2350 |
3/4/09 |
F-198 |
6 |
$5.25 |
Adventure Works |
1025 Columbia Circle Kirkland, WA 98234 |
425-555-0185 |
Adams, Ellen |
2350 |
3/4/09 |
B-205 |
1 |
$4.50 |
Adventure Works |
1025 Columbia Circle Kirkland, WA 98234 |
425-555-0185 |
Hance, Jim |
2351 |
3/4/09 |
C-795 |
6 |
$9.75 |
Contoso, Ltd. |
2302 Harvard Ave Bellevue, WA 98227 |
425-555-0222 |
Hance, Jim |
2352 |
3/5/09 |
A-2275 |
2 |
$16.75 |
Adventure Works |
1025 Columbia Circle Kirkland, WA 98234 |
425-555-0185 |
Hance, Jim |
2352 |
3/5/09 |
D-4420 |
3 |
$7.25 |
Adventure Works |
1025 Columbia Circle Kirkland, WA 98234 |
425-555-0185 |
Koch, Reed |
2353 |
3/7/09 |
A-2275 |
6 |
$16.75 |
Fourth Coffee |
7007 Cornell St Redmond, WA 98199 |
425-555-0201 |
Koch, Reed |
2353 |
3/7/09 |
C-789 |
5 |
$7.00 |
Fourth Coffee |
7007 Cornell St Redmond, WA 98199 |
425-555-0201 |
Information in its smallest parts: atomic data
Working with the data in this example, you can use the Text to Column command in Excel to separate the «atomic» parts of a cell (such as street address, city, state, and postal code) into discrete columns.
The following table shows the new columns in the same worksheet after they have been split to make all values atomic. Note that the information in the Salesperson column has been split into Last Name and the First Name columns and that the information in the Address column has been split into Street Address, City, State, and ZIP Code columns. This data is in «first normal form.»
Last Name |
First Name |
Street Address |
City |
State |
ZIP Code |
|
---|---|---|---|---|---|---|
Li |
Yale |
2302 Harvard Ave |
Bellevue |
WA |
98227 |
|
Adams |
Ellen |
1025 Columbia Circle |
Kirkland |
WA |
98234 |
|
Hance |
Jim |
2302 Harvard Ave |
Bellevue |
WA |
98227 |
|
Koch |
Reed |
7007 Cornell St Redmond |
Redmond |
WA |
98199 |
Breaking data out into organized subjects in Excel
The several tables of example data that follow show the same information from the Excel worksheet after it has been split into tables for salespersons, products, customers, and orders. The table design isn’t final, but it’s on the right track.
The Salespersons table contains only information about sales personnel. Note that each record has a unique ID (SalesPerson ID). The SalesPerson ID value will be used in the Orders table to connect orders to salespeople.
Salespersons |
||
---|---|---|
Salesperson ID |
Last Name |
First Name |
101 |
Li |
Yale |
103 |
Adams |
Ellen |
105 |
Hance |
Jim |
107 |
Koch |
Reed |
The Products table contains only information about products. Note that each record has a unique ID (Product ID). The Product ID value will be used to connect product information to the Order Details table.
Products |
|
---|---|
Product ID |
Price |
A-2275 |
16.75 |
B-205 |
4.50 |
C-789 |
7.00 |
C-795 |
9.75 |
D-4420 |
7.25 |
F-198 |
5.25 |
The Customers table contains only information about customers. Note that each record has a unique ID (Customer ID). The Customer ID value will be used to connect customer information to the Orders table.
Customers |
||||||
---|---|---|---|---|---|---|
Customer ID |
Name |
Street Address |
City |
State |
ZIP Code |
Phone |
1001 |
Contoso, Ltd. |
2302 Harvard Ave |
Bellevue |
WA |
98227 |
425-555-0222 |
1003 |
Adventure Works |
1025 Columbia Circle |
Kirkland |
WA |
98234 |
425-555-0185 |
1005 |
Fourth Coffee |
7007 Cornell St |
Redmond |
WA |
98199 |
425-555-0201 |
The Orders table contains information about orders, salespersons, customers, and products. Note that each record has a unique ID (Order ID). Some of the information in this table needs to be split into an additional table that contains order details so that the Orders table contains only four columns — the unique order ID, the order date, the salesperson ID, and the customer ID. The table shown here has not yet been split into the Order Details table.
Orders |
|||||
---|---|---|---|---|---|
Order ID |
Order Date |
SalesPerson ID |
Customer ID |
Product ID |
Qty |
2349 |
3/4/09 |
101 |
1005 |
C-789 |
3 |
2349 |
3/4/09 |
101 |
1005 |
C-795 |
6 |
2350 |
3/4/09 |
103 |
1003 |
A-2275 |
2 |
2350 |
3/4/09 |
103 |
1003 |
F-198 |
6 |
2350 |
3/4/09 |
103 |
1003 |
B-205 |
1 |
2351 |
3/4/09 |
105 |
1001 |
C-795 |
6 |
2352 |
3/5/09 |
105 |
1003 |
A-2275 |
2 |
2352 |
3/5/09 |
105 |
1003 |
D-4420 |
3 |
2353 |
3/7/09 |
107 |
1005 |
A-2275 |
6 |
2353 |
3/7/09 |
107 |
1005 |
C-789 |
5 |
Order details, such as the product ID and quantity are moved out of the Orders table and stored in a table named Order Details. Keep in mind that there are 9 orders, so it makes sense that there are 9 records in this table. Note that the Orders table has a unique ID (Order ID), which will referred to from the Order Details table.
The final design of the Orders table should look like the following:
Orders |
|||
---|---|---|---|
Order ID |
Order Date |
SalesPerson ID |
Customer ID |
2349 |
3/4/09 |
101 |
1005 |
2350 |
3/4/09 |
103 |
1003 |
2351 |
3/4/09 |
105 |
1001 |
2352 |
3/5/09 |
105 |
1003 |
2353 |
3/7/09 |
107 |
1005 |
The Order Details table contains no columns that require unique values (that is, there is no primary key), so it is okay for any or all columns to contain «redundant» data. However, no two records in this table should be completely identical (this rule applies to any table in a database). In this table, there should be 17 records — each corresponding to a product in an individual order. For example, in order 2349, three C-789 products comprise one of the two parts of the entire order.
The Order Details table should, therefore, look like the following:
Order Details |
||
---|---|---|
Order ID |
Product ID |
Qty |
2349 |
C-789 |
3 |
2349 |
C-795 |
6 |
2350 |
A-2275 |
2 |
2350 |
F-198 |
6 |
2350 |
B-205 |
1 |
2351 |
C-795 |
6 |
2352 |
A-2275 |
2 |
2352 |
D-4420 |
3 |
2353 |
A-2275 |
6 |
2353 |
C-789 |
5 |
Copying and pasting data from Excel into Access
Now that the information about salespersons, customers, products, orders, and order details has been broken out into separate subjects in Excel, you can copy that data directly into Access, where it will become tables.
Creating relationships between the Access tables and running a query
After you have moved your data to Access, you can create relationships between tables and then create queries to return information about various subjects. For example, you can create a query that returns the Order ID and the names of the salespersons for orders entered between 3/05/09 and 3/08/09.
In addition, you can create forms and reports to make data entry and sales analysis easier.
Need more help?
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
Note: Microsoft Access doesn’t support importing Excel data with an applied sensitivity label. As a workaround, you can remove the label before importing and then re-apply the label after importing. For more information, see Apply sensitivity labels to your files and email in Office.
You can bring the data from an Excel workbook into Access databases in many ways. You can copy data from an open worksheet and paste it into an Access datasheet, import a worksheet into a new or existing table, or link to a worksheet from an Access database.
This topic explains in detail how to import or link to Excel data from Access desktop databases.
What do you want to do?
-
Understand importing data from Excel
-
Import data from Excel
-
Troubleshoot missing or incorrect values
-
Link to data in Excel
-
Troubleshoot #Num! and other incorrect values in a linked table
Understand importing data from Excel
If your goal is to store some or all of your data from one or more Excel worksheets in Access, you should import the contents of the worksheet into a new or existing Access database. When you import data, Access creates a copy of the data in a new or existing table without altering the source Excel worksheet.
Common scenarios for importing Excel data into Access
-
You are a long-time user of Excel but, going forward, you want to use Access to work with this data. You want to move the data in your Excel worksheets into one or more new Access databases.
-
Your department or workgroup uses Access, but you occasionally receive data in Excel format that must be merged with your Access databases. You want to import these Excel worksheets into your database as you receive them.
-
You use Access to manage your data, but the weekly reports you receive from the rest of your team are Excel workbooks. You would like to streamline the import process to ensure that data is imported every week at a specific time into your database.
If this is the first time you are importing data from Excel
-
There is no way to save an Excel workbook as an Access database. Excel does not provide functionality to create an Access database from Excel data.
-
When you open an Excel workbook in Access (in the File Open dialog box, change the Files of Type list box to Microsoft Office Excel Files and select the file you want), Access creates a link to the workbook instead of importing its data. Linking to a workbook is fundamentally different from importing a worksheet into a database. For more information about linking, see the section Link to data in Excel, later in this article.
Import data from Excel
The steps in this section explain how to prepare for and run an import operation, and how to save the import settings as a specification for later reuse. As you proceed, remember that you can import data from only one worksheet at a time. You cannot import all the data from a whole workbook at the same time.
Prepare the worksheet
-
Locate the source file and select the worksheet that contains the data that you want to import to Access. If you want to import only a portion of a worksheet, you can define a named range that includes only the cells that you want to import.
Define a named range (optional)
-
Switch to Excel and open the worksheet that has data that you want to import.
-
Select the range of cells that contain the data that you want to import.
-
Right-click within the selected range and then click Name a Range or Define Name.
-
In the New Name dialog box, specify a name for the range in the Name box and click OK.
Remember that you can import only one worksheet at a time during an import operation. To import data from multiple worksheets, repeat the import operation for each worksheet.
-
-
Review the source data and take action as described in this table.
Element
Description
Number of columns
The number of source columns that you want to import cannot exceed 255, because Access does not support more than 255 fields in a table.
Skipping columns and rows
It is a good practice to include only the rows and columns that you want to import in the source worksheet or named range.
Rows You cannot filter or skip rows during the import operation.
Columns You cannot skip columns during the operation if you choose to add the data to an existing table.
Tabular format
Ensure that the cells are in tabular format. If the worksheet or named range includes merged cells, the contents of the cell are placed in the field that corresponds to the leftmost column, and the other fields are left blank.
Blank columns, rows, and cells
Delete all unnecessary blank columns and blank rows in the worksheet or range. If the worksheet or range contains blank cells, try to add the missing data. If you are planning to append the records to an existing table, ensure that the corresponding field in the table accepts null (missing or unknown) values. A field will accept null values if its Required field property is set to No and its ValidationRule property setting doesn’t prevent null values.
Error values
If one or more cells in the worksheet or range contain error values, such as #NUM and #DIV, correct them before you start the import operation. If a source worksheet or range contains error values, Access places a null value in the corresponding fields in the table. For more information about ways to correct those errors, see the section Troubleshoot missing or incorrect values, later in this article.
Data type
To avoid errors during importing, ensure that each source column contains the same type of data in every row. Access scans the first eight source rows to determine the data type of the fields in the table. We highly recommend that you ensure that the first eight source rows do not mix values of different data types in any of the columns. Otherwise, Access might not assign the correct data type to the column.
Also, it is a good practice to format each source column in Excel and assign a specific data format to each column before you start the import operation. Formatting is highly recommended if a column includes values of different data types. For example, the FlightNo column in a worksheet might contain numeric and text values, such as 871, AA90, and 171. To avoid missing or incorrect values, do the following:
-
Right-click the column header and then click Format Cells.
-
On the Number tab, under Category, select a format. For the FlightNo column, you would probably choose Text.
-
Click OK.
If the source columns are formatted, but still contain mixed values in the rows following the eighth row, the import operation might still skip values or convert values incorrectly. For troubleshooting information, see the section Troubleshoot missing or incorrect values.
First row
If the first row in the worksheet or named range contains the names of the columns, you can specify that Access treat the data in the first row as field names during the import operation. If your source worksheet or range doesn’t include the names, it is a good idea to add them to the source before you start the import operation.
Note: If you plan to append the data to an existing table, ensure that the name of each column exactly matches the name of the corresponding field. If the name of a column is different from the name of the corresponding field in the table, the import operation will fail. To see the names of the fields, open the table in Design view in Access.
-
-
Close the source workbook, if it is open. Keeping the source file open might result in data conversion errors during the import operation.
Prepare the destination database
-
Open the Access database where the imported data will be stored. Ensure that the database is not read-only, and that you have permissions to make changes to the database.
-or-
If you don’t want to store the data in any of your existing databases, create a blank database. To do so:
Click the File tab, click New, and then click Blank Database.
-
Before you start the import operation, decide whether you want to store the data in a new or existing table.
Create a new table If you choose to store the data in a new table, Access creates a table and adds the imported data to this table. If a table with the specified name already exists, Access overwrites the contents of the table with the imported data.
Append to an existing table If you choose to add the data to an existing table, the rows in the Excel worksheet are appended to the specified table.
Remember that most failures during append operations occur because the source data does not match the structure and field settings of the destination table. To avoid this, open the destination table in Design view and review the following:
-
First row If the first row of the source worksheet or named range does not contain column headings, ensure that the position and data type of each column in the source worksheet matches those of the corresponding field in the table. If the first row contains column headings, the order of columns and fields do not need to match, but the name and data type of each column must exactly match those of its corresponding field.
-
Missing or extra fields If one or more fields in the source worksheet do not exist in the destination table, add them before you start the import operation. However, if the table contains fields that don’t exist in the source, you do not need to delete those fields from the table if they accept null values.
Tip: A field will accept null values if its Required property is set to No and its ValidationRule property setting doesn’t prevent null values.
-
Primary key If the table contains a primary key field, the source worksheet or range must have a column that contains values that are compatible with the primary key field, and the imported key values must be unique. If an imported record contains a primary key value that already exists in the destination table, the import operation displays an error message.
-
Indexed fields If the Indexed property of a field in the table is set to Yes (No Duplicates), the corresponding column in the source worksheet or range must contain unique values.
Go to the next steps to run the import operation.
-
Start the import operation
-
The location of the import/link wizard differs slightly depending upon your version of Access. Choose the steps that match your Access version:
-
If you’re using the latest version of the Microsoft 365 subscription version of Access or Access 2019, on the External Data tab, in the Import & Link group, click New Data Source > From File > Excel.
-
If you’re using Access 2016, Access 2013, or Access 2010, on the External Data tab, in the Import & Link group, click Excel.
Note: The External Data tab is not available unless a database is open.
-
-
In the Get External Data — Excel Spreadsheet dialog box, in the File name box, specify the name of the Excel file that contains the data that you want to import.
-or-
Click Browse and use the File Open dialog box to locate the file that you want to import.
-
Specify how you want to store the imported data.
To store the data in a new table, select Import the source data into a new table in the current database. You will be prompted to name this table later.
To append the data to an existing table, select Append a copy of the records to the table and select a table from the drop-down list. This option is not available if the database has no tables.
To link to the data source by creating a linked table, see the section Link to data in Excel, later in this article.
-
Click OK.
The Import Spreadsheet Wizard starts, and leads you through the import process. Go to the next set of steps.
Use the Import Spreadsheet wizard
-
On the first page of the wizard, select the worksheet that contains the data that you want to import, and then click Next.
-
On the second page of the wizard, click either Show Worksheets or Show Named Ranges, select either the worksheet or the named range that you want to import, and then click Next.
-
If the first row of the source worksheet or range contains the field names, select First Row Contains Column Headings and click Next.
If you are importing the data into a new table, Access uses these column headings to name the fields in the table. You can change these names either during or after the import operation. If you are appending the data to an existing table, ensure that the column headings in the source worksheet exactly match the names of the fields in the destination table.
If you are appending data to an existing table, skip directly to step 6. If you are adding the data to a new table, follow the remaining steps.
-
The wizard prompts you to review the field properties. Click a column in the lower half of the page to display the corresponding field’s properties. Optionally, do any of the following:
-
Review and change, if you want, the name and data type of the destination field.
Access reviews the first eight rows in each column to suggest the data type for the corresponding field. If the column in the worksheet contains different types of values, such as text and numbers, in the first eight rows of a column, the wizard suggests a data type that is compatible with all the values in the column — most often, the text data type. Although you can choose a different data type, remember that values that are incompatible with the data type that you choose will be either ignored or converted incorrectly during the import process. For more information about how to correct missing or incorrect values, see the section Troubleshoot missing or incorrect values, later in this article.
-
To create an index on the field, set Indexed to Yes.
-
To completely skip a source column, select the Do not import field (Skip) check box.
Click Next after you finish selecting options.
-
-
In the next screen, specify a primary key for the table. If you select Let Access add primary key, Access adds an AutoNumber field as the first field in the destination table, and automatically populates it with unique ID values, starting with 1. Click Next.
-
In the final wizard screen, specify a name for the destination table. In the Import to Table box, type a name for the table. If the table already exists, Access displays a prompt that asks whether you want to overwrite the existing contents of the table. Click Yes to continue or No to specify a different name for the destination table, and then click Finish to import the data.
If Access was able to import some or all the data, the wizard displays a page that shows you the status of the import operation. In addition, you can save the details of the operation for future use as a specification. Conversely, if the operation completely failed, Access displays the message An error occurred trying to import file.
-
Click Yes to save the details of the operation for future use. Saving the details helps you repeat the operation at a later time without having to step through the wizard each time.
See Save the details of an import or export operation as a specification to learn how to save your save your specification details.
See Run a saved import or export specification to learn how to run your saved import or link specifications.
See Schedule an import or export specification to learn how to schedule import and link tasks to run at specific times.
Troubleshoot missing or incorrect values
If you receive the message An error occurred trying to import file, the import operation completely failed. Conversely, if the import operation displays a dialog box that prompts you to save the details of the operation, the operation was able to import all or some of the data. The status message also mentions the name of the error log table that contains the description of any errors that occurred during the import operation.
Important: Even if the status message indicates a completely successful operation, you should review the contents and structure of the table to ensure that everything looks correct before you start using the table.
-
Open the destination table in Datasheet view to see whether all data was added to the table.
-
Open the table in Design view to review the data type and other property settings of the fields.
The following table describes the steps that you can take to correct missing or incorrect values.
Tip: While you are troubleshooting the results, if you find just a few missing values, you can add them to the table manually. Conversely, if you find that entire columns or a large number of values are either missing or were not imported properly, you should correct the problem in the source file. After you have corrected all known problems, repeat the import operation.
Issue |
Resolution |
||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Graphical elements |
Graphical elements, such as logos, charts, and pictures cannot be imported. Manually add them to the database after completing the import operation. |
||||||||||||
Calculated values |
The results of a calculated column or cells are imported, but not the underlying formula. During the import operation, you can specify a data type that is compatible with the formula results, such as Number. |
||||||||||||
TRUE or FALSE and -1 or 0 values |
If the source worksheet or range includes a column that contains only TRUE or FALSE values, Access creates a Yes/No field for the column and inserts -1 or 0 values in the field. However, if the source worksheet or range includes a column that contains only -1 or 0 values, Access, by default, creates a numeric field for the column. You can change the data type of the field to Yes/No during the import operation to avoid this problem. |
||||||||||||
Multivalued fields |
When you import data to a new table or append data to an existing table, Access does not enable support for multiple values in a field, even if the source column contains a list of values separated by semicolon (;). The list of values is treated as a single value and is placed in a text field. |
||||||||||||
Truncated data |
If data appears truncated in a column in the Access table, try increasing the width of the column in Datasheet view. If that doesn’t resolve the issue, the data in a numeric column in Excel is too large for the field size of the destination field in Access. For example, the destination field might have the FieldSize property set to Byte in an Access database but the source data contains a value greater than 255. Correct the values in the source file and try importing again. |
||||||||||||
Display format |
You might have to set the Format property of certain fields in design view to ensure that the values are displayed correctly in Datasheet view. For example:
Note: If the source worksheet contains rich text formatting such as bold, underline, or italics, the text is imported, but the formatting is lost. |
||||||||||||
Duplicate values (key violation error) |
Records that you are importing might contain duplicate values that cannot be stored in the primary key field of the destination table or in a field that has the Indexed property set to Yes (No Duplicates). Eliminate the duplicate values in the source file and try importing again. |
||||||||||||
Date values off by 4 years |
The date fields that are imported from an Excel worksheet might be off by four years. Excel for Windows can use two date systems:
You can set the date system in Excel Options: File > Options > Advanced > Use 1904 date system. Note If you import from a .xlsb workbook, it always uses the 1900 Date System regardless of the Date System setting. Before you import the data, change the date system for the Excel workbook or, after appending the data, perform an update query that uses the expression [date field name] + 1462 to correct the dates. Excel for the Macintosh only uses the 1904 Date System. |
||||||||||||
Null values |
You might see an error message at the end of the import operation about data that was deleted or lost during the operation, or when you open the table in Datasheet view, you might see that some field values are blank. If the source columns in Excel are not formatted, or the first eight source rows contain values of different data types, open the source worksheet and do the following:
The preceding steps can help minimize the appearance of null values. The following table lists cases in which you will still see null values:
|
||||||||||||
Date values replaced by numeric values |
You will see seemingly random five-digit numbers instead of the actual date values in the following situations:
|
||||||||||||
Numeric values replaced by date values |
You will see seemingly random date values instead of the actual numeric values in the following situations:
To avoid this, replace the numeric values with date values in the source column and then try importing again. |
In addition, you might want to review the error log table (mentioned in the last page of the wizard) in Datasheet view. The table has three fields — Error, Field, and Row. Each row contains information about a specific error, and the contents of the Error field should help you troubleshoot the problem.
Error strings and troubleshooting hints
Error |
Description |
---|---|
Field Truncation |
A value in the file is too large for the FieldSize property setting for this field. |
Type Conversion Failure |
A value in the worksheet is the wrong data type for this field. The value might be missing or might appear incorrect in the destination field. See the previous table for more information how to troubleshoot this issue. |
Key Violation |
This record’s primary key value is a duplicate — it already exists in the table. |
Validation Rule Failure |
A value breaks the rule set by using the ValidationRule property for this field or for the table. |
Null in Required Field |
A null value isn’t allowed in this field because the Required property for the field is set to Yes. |
Null value in AutoNumber field |
The data that you are importing contains a Null value that you attempted to append to an AutoNumber field. |
Unparsable Record |
A text value contains the text delimiter character (usually double quotation marks). Whenever a value contains the delimiter character, the character must be repeated twice in the text file; for example: 4 1/2″» diameter |
Top of Page
Link to data in Excel
By linking an Access database to data in another program, you can use the querying and reporting tools that Access provides without having to maintain a copy of the Excel data in your database.
When you link to an Excel worksheet or a named range, Access creates a new table that is linked to the source cells. Any changes that you make to the source cells in Excel appear in the linked table. However, you cannot edit the contents of the corresponding table in Access. If you want to add, edit, or delete data, you must make the changes in the source file.
Common scenarios for linking to an Excel worksheet from within Access
Typically, you link to an Excel worksheet (instead of importing) for the following reasons:
-
You want to continue to keep your data in Excel worksheets, but be able to use the powerful querying and reporting features of Access.
-
Your department or workgroup uses Access, but data from external sources that you work with is in Excel worksheets. You don’t want to maintain copies of external data, but want to be able to work with it in Access.
If this is the first time you are linking to an Excel worksheet
-
You cannot create a link to an Access database from within Excel.
-
When you link to an Excel file, Access creates a new table, often referred to as a linked table. The table shows the data in the source worksheet or named range, but it doesn’t actually store the data in the database.
-
You cannot link Excel data to an existing table in the database. This means that you cannot append data to an existing table by performing a linking operation.
-
A database can contain multiple linked tables.
-
Any changes that you make to the data in Excel are automatically reflected in the linked table. However, the contents and structure of a linked table in Access are read-only.
-
When you open an Excel workbook in Access (in the File Open dialog box, change the Files of Type list box to Microsoft Excel, and select the file you want), Access creates a blank database and automatically starts the Link Spreadsheet Wizard.
Prepare the Excel data
-
Locate the Excel file and the worksheet or range that has the data you want to link to. If you don’t want to link to the entire worksheet, consider defining a named range that includes only the cells you want to link to.
Create a named range in Excel (optional – useful if you only want to link to some of the worksheet data)
-
Switch to Excel and display the worksheet in which you want to define a named range.
-
Select the range of cells that contain the data you want to link to.
-
Right-click within the selected range and click Name a Range or Define Name.
-
In the New Name dialog box, specify a name for the range in the Name box and then click OK.
Note that you can link to only one worksheet or range at a time during a link operation. To link to data in multiple places in a workbook, repeat the link operation for each worksheet or range.
-
-
Review the source data, and take action as described in the following table:
Element
Description
Tabular format
Ensure that the cells are in tabular format. If the range includes merged cells, the contents of the cell are placed in the field that corresponds to the leftmost column and the other fields are left blank.
Skipping columns and rows
You cannot skip source columns and rows during the linking operation. However, you can hide fields and filter records by opening the linked table in Datasheet view after you have imported them into Access.
Number of columns
The number of source columns cannot exceed 255, because Access does not support more than 255 fields in a table.
Blank columns, rows, and cells
Delete all unnecessary blank columns and blank rows in the Excel worksheet or range. If there are blank cells, try to add the missing data.
Error values
If one or more cells in a worksheet or range contain error values, correct them before you start the import operation. Note that if a source worksheet or range contains error values, Access inserts a null value in the corresponding fields in the table.
Data type
You cannot change the data type or size of the fields in the linked table. Before you start the linking operation, you must verify that each column contains data of a specific type.
We highly recommend that you format a column if it includes values of different data types. For example, the FlightNo column in a worksheet might contain numeric and text values, such as 871, AA90, and 171. To avoid missing or incorrect values, do the following:
-
Right-click the column and then click Format Cells.
-
On the Number tab, under Category, select a format.
-
Click OK.
First row
If the first row in the worksheet or named range contains the names of the columns, you can specify that Access should treat the data in the first row as field names during the link operation. If there are no column names in the worksheet, or if a specific column name violates the field naming rules in Access, Access assigns a valid name to each corresponding field.
-
-
Close the source file, if it is open.
Prepare the destination database
-
Open the database in which you want to create the link. Ensure that the database is not read-only and that you have the necessary permissions to make changes to it.
-
If you don’t want to store the link in any of your existing databases, create a blank database: Click the File tab, click New, and then click Blank Database. Note, if you’re using Access 2007, click the Microsoft Office Button and then click New.
You are now ready to start the linking operation.
Create the link
-
The location of the import/link wizard differs slightly depending upon your version of Access. Choose the steps that match your Access version:
-
If you’re using the latest version of the Microsoft 365 subscription version of Access or Access 2019, on the External Data tab, in the Import & Link group, click New Data Source > From File > Excel.
-
If you’re using Access 2016, Access 2013, or Access 2010, on the External Data tab, in the Import & Link group, click Excel.
Note: The External Data tab is not available unless a database is open.
-
-
In the Get External Data — Excel Spreadsheet dialog box, in the File name box, specify the name of the Excel source file.
-
Select Link to the data source by creating a linked table, and then click OK.
The Link Spreadsheet Wizard starts and guides you through the linking process.
-
On the first page of the wizard, select a worksheet or a named range and click Next.
-
If the first row of the source worksheet or range contains the field names, select First row contains column headings. Access uses these column headings to name the fields in the table. If a column name includes certain special characters, it cannot be used as a field name in Access. In such cases, an error message is displayed that tells you that Access will assign a valid name for the field. Click OK to continue.
-
On the final page of the wizard, specify a name for the linked table and then click Finish. If the table with the name you specify already exists, you are asked if you want to overwrite the existing table or query. Click Yes if you want to overwrite the table or query, or click No to specify a different name.
Access tries to create the linked table. If the operation succeeds, Access displays the Finished linking table message. Open the linked table and review the fields and data to ensure that you see the correct data in all the fields.
If you see error values or incorrect data, you must troubleshoot the source data. For more information about how to troubleshoot error values or incorrect values, see the next section.
Top of Page
Troubleshoot #Num! and other incorrect values in a linked table
Even if you receive the message Finished linking table, you should open the table in Datasheet view to ensure that the rows and columns show the correct data.
If you see errors or incorrect data anywhere in the table, take correct action as described in the following table, and then try linking again. Remember that you cannot add the values directly to the linked table, because the table is read-only.
Issue |
Resolution |
---|---|
Graphical elements |
Graphical elements in an Excel worksheet, such as logos, charts, and pictures, cannot be linked to in Access. |
Display format |
You might have to set the Format property of certain fields in Design view to ensure that the values are displayed correctly in Datasheet view. |
Calculated values |
The results of a calculated column or cells are displayed in the corresponding field, but you cannot view the formula (or expression) in Access. |
Truncated text values |
Increase the width of the column in Datasheet view. If you still don’t see the entire value, it could be because the value is longer than 255 characters. Access can only link to the first 255 characters, so you should import the data instead of linking to it. |
Numeric field overflow error message |
The linked table might appear to be correct, but later, when you run a query against the table, you might see a Numeric Field Overflow error message. This can happen because of a conflict between the data type of a field in the linked table and the type of data that is stored in that field. |
TRUE or FALSE and -1 or 0 values |
If the source worksheet or range includes a column that contains only TRUE or FALSE values, Access creates a Yes/No field for the column in the linked table. However, if the source worksheet or range includes a column that contains only -1 or 0 values, Access, by default, creates a numeric field for the column, and you will not be able to change the data type of the corresponding field in the table. If you want a Yes/No field in the linked table, ensure that the source column includes TRUE and FALSE values. |
Multivalued fields |
Access does not enable support for multiple values in a field, even if the source column contains a list of values separated by semicolon (;). The list of values will be treated as a single value, and placed in a text field. |
#Num! |
Access displays the #Num! error value instead of the actual data in a field in the following situations:
Do the following to minimize the instances of null values in the table:
|
Numeric values instead of date values |
If you see a seemingly random five-digit number in a field, check to see if the source column contains mostly numeric values but also includes a few date values. Date values that appear in numeric columns get incorrectly converted to a number. Replace the date values with numeric values and then try linking again. |
Date values instead of numeric values |
If you see a seemingly random date value in a field, check to see if the source column contains mostly date values but also includes a few numeric values. Numeric values that appear in date columns get incorrectly converted to a date. Replace the numeric values with date values and then try linking again. |
Top of Page
Download Article
Download Article
Access is a relational database manager that allows you to import one or multiple Excel databases into its system so you can match common fields between or among them. Because a single Access file can contain multiple Excel spreadsheets, the program is also a great way to aggregate or analyze large amounts of information. First, though, you need to import the Excel spreadsheet into Access. This only requires a few key steps.
Things You Should Know
- Before you import your spreadsheet into Access, make sure you have clear column headers in the first row so they can easily translate to field names.
- Scan multi-page workbooks to make sure each type of data is handled the same way across all sheets.
- The Access import wizard makes it easy to import your data in a way that Access can understand.
-
1
Open both programs on your computer. You will need to purchase and download a Microsoft Office package that includes both Excel[1]
and Access. You can do this online through the Microsoft site.- Once the programs are downloaded, click «Start» in Windows and select «All Programs.»[2]
- Click on «Microsoft Office,» and then select «Access» (or «Excel») from the drop-down menu. You may already have an Excel spreadsheet created that someone else sent you or that you downloaded from elsewhere. Having Office on your computer allows you to open it.
- Once the programs are downloaded, click «Start» in Windows and select «All Programs.»[2]
-
2
Clean up your Excel spreadsheet before importing it into Access. It will make it easier if you do a few simple steps before you import the Excel spreadsheet into Access. The key is that your data must be consistent between imported spreadsheets.[3]
- It’s a good idea to make sure that the first row in the Excel spreadsheet contains your column headers (or field names), and that these are very clear and easy to understand.[4]
For example, for a column containing people’s last names, you may want to call the column header/field name «last name.» Be clear and precise because it will make it easier when you try to match column headers in one Excel sheet with another. - Access allows you to link common fields between two or among many spreadsheets. Let’s say you have an Excel sheet that contains payroll information. It includes people’s first and last names, addresses, and salaries. Let’s say for the sake of argument that you want to match that sheet within Access to a second Excel sheet that contains information about campaign finance contributions. This second sheet contains people’s names, addresses, and donations. What Access allows you to do is to match different column headers with one another. You could link name headers to see which people of the same name appear in both databases, for example.
- Scan the Excel sheets to make sure that each type of data is handled the same way, and clean it up before importing it into Access.[5]
It must be what Access calls «relational.» For example, if the hypothetical spreadsheet for payroll contained first name, last name and middle initial in one column, but the second spreadsheet contained only first name and last name in separate columns, Access will register this as no match. There needs to be matching column headers/fields.
Advertisement
- It’s a good idea to make sure that the first row in the Excel spreadsheet contains your column headers (or field names), and that these are very clear and easy to understand.[4]
-
3
Split information within a column in Excel. To take care of this issue, you may want to split information in a column within Excel, so that it doesn’t erroneously register as a «no match» in Access.
- As an example, you may want to split the first name into its own column, the middle initial into its own column, and the last name into its own column. If it’s already done the same way in the second spreadsheet, when you link, say, last name with last name in Access, it should generate matches when the names are the same.
- To split a column in Excel, highlight the column that has information you want to split in it. Click on «data»in the toolbar within the Excel program. Click on «text to columns.» Generally, you will choose the option «delimited.» Click next.
-
4
Continue using the wizard to split merged columns. Now you are ready to complete the process of splitting merged information in one column into multiple columns.
- Choose how the data within the column is «delimited.» This means that each piece of information in the column is separated by something. Most common choices include a space, a comma, or a semi-colon. Often the information is just separated by a space. As in the following example: let’s say the name «John A. Doe» appears in a single column. The first name John is separated from the middle initial A by a space. The last name Doe is separated from the middle initial A by a space. So choose space in the delimited wizard.
- Click next. Click finish. The program should split John, A., and Doe into three columns. You can then give the new columns new header names to indicate the kind of information housed in them (last name, first name, etc.). It’s a good idea to create several blank columns to the right of the data you’re splitting before you do it because it will push the data into the new blank columns (instead of columns that already contain information).
Advertisement
-
1
Open the Access program on your computer. Go to the start menu, choose Microsoft Office, and click on Microsoft Access. You need to open a new blank Access database to import the Excel sheet into it.
- Choose «blank desktop database» to create a new database within the Access program.
- Give it a new name if you want. Click «create.»
-
2
Import an Excel spreadsheet into Access. The next step is to pull the Excel spreadsheet (or more than one) into the Access database.
- Click on «External Data» in the toolbar once you are within the Access database manager. Choose «Excel.»[6]
In some versions of Access, you will find this function by clicking on «file» in the toolbar and «Get External Data.»[7]
- Where it says «file name,» click «browse.» This will allow you to find your Excel sheet on your computer.
- Leave the box checked that says «import the source data into a new table in the current database.» It will be checked by default.
- When you find the Excel spreadsheet you want to import on your computer, click on it. Click «OK.» This will take you into the wizard for importing Excel into Access.
- Click on «External Data» in the toolbar once you are within the Access database manager. Choose «Excel.»[6]
Advertisement
-
1
Go through the steps on the wizard that appears within Access. To complete the process of importing your spreadsheet, you need to complete the steps in the wizard.
- Choose the worksheet within the Excel spreadsheet that you want to import. Sometimes, this is simple because the Excel spreadsheet is just one sheet. However, sometimes people create multiple pages within a single Excel spreadsheet, which you can see by clicking on the tabs at the bottom of the spreadsheet. If this is the case, you need to tell the Access wizard which spreadsheet you are choosing. Click next.
- The next page has a box asking if the first row in the Excel sheet has column headings. This means the row in a spreadsheet that identifies the data in each column (such as last name, address, salary, etc.). It’s a good idea if you cleaned up your Excel sheet first to make sure that the first row has clearly defined column headings. Then, just check yes that the first row contains column headings. This is the simplest approach. Click next.
- If your first row does not contain column headings, the next page asks you if you want to rename what are called «fields» in Access (these are column headings). If you did not already name each field something clear and easy to recognize before importing (recommended), then you can do it here.
-
2
Finish the importing process. There are only a few steps left in the importing process. The next page in the wizard will ask if you want to identify a primary key.
- You don’t have to do this, but you can. A primary key means the computer program will assign each row of information a unique number. This can be helpful later on when sorting the data. Click next.[8]
- The final screen in the wizard has a space providing a default name. You can change the name of the Excel sheet you are importing (it will become a «table» in Access on the left side of the page when you finish importing it).
- Click «import.» Click «close.» You will see your table on the left side of the screen. It is now imported within Access.
- If you want to link more than one data set, repeat this process with another or multiple Excel spreadsheets. Now, you are ready to match the data in the sheets within Access.
- You don’t have to do this, but you can. A primary key means the computer program will assign each row of information a unique number. This can be helpful later on when sorting the data. Click next.[8]
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Video
Thanks for submitting a tip for review!
-
If the Excel file is from a different version of Office than Access, you may have trouble importing files smoothly.
-
It can’t be underscored enough: You need to clean up your Excel spreadsheet before importing it. Partly this means analyzing the data you have for problems.
-
Always keep a copy of your original spreadsheets, so if you mess them up, you can repeat the process.
-
You can not import more than 255 fields into Access.[9]
Advertisement
About This Article
Thanks to all authors for creating a page that has been read 263,833 times.
Is this article up to date?
This tutorial will cover the ways to import data from Excel into an Access Table and ways to export Access objects (Queries, Reports, Tables, or Forms) to Excel.
Import Excel File Into Access
To import an Excel file to Access, use the acImport option of DoCmd.TransferSpreadsheet :
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "Table1", "C:TempBook1.xlsx", True
Or you can use DoCmd.TransferText to import a CSV file:
DoCmd.TransferText acLinkDelim, , "Table1", "C:TempBook1.xlsx", True
Import Excel to Access Function
This function can be used to import an Excel file or CSV file into an Access Table:
Public Function ImportFile(Filename As String, HasFieldNames As Boolean, TableName As String) As Boolean
' Example usage: call ImportFile ("Select an Excel File", "Excel Files", "*.xlsx", "C:" , True,True, "ExcelImportTest", True, True,false,True)
On Error GoTo err_handler
If (Right(Filename, 3) = "xls") Or ((Right(Filename, 4) = "xlsx")) Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, TableName, Filename, blnHasFieldNames
End If
If (Right(Filename, 3) = "csv") Then
DoCmd.TransferText acLinkDelim, , TableName, Filename, True
End If
Exit_Thing:
'Clean up
'Check if our linked in Excel table already exists... and delete it if so
If ObjectExists("Table", TableName) = True Then DropTable (TableName)
Set colWorksheets = Nothing
Exit Function
err_handler:
If (Err.Number = 3086 Or Err.Number = 3274 Or Err.Number = 3073) And errCount < 3 Then
errCount = errCount + 1
ElseIf Err.Number = 3127 Then
MsgBox "The fields in all the tabs are the same. Please make sure that each sheet has the exact column names if you wish to import mulitple", vbCritical, "MultiSheets not identical"
ImportFile = False
GoTo Exit_Thing
Else
MsgBox Err.Number & " - " & Err.Description
ImportFile = False
GoTo Exit_Thing
Resume
End If
End Function
You can call the function like this:
Private Sub ImportFile_Example()
Call VBA_Access_ImportExport.ImportFile("C:TempBook1.xlsx", True, "Imported_Table_1")
End Sub
Access VBA Export to New Excel File
To export an Access object to a new Excel file, use the DoCmd.OutputTo method or the DoCmd.TransferSpreadsheet method:
Export Query to Excel
This line of VBA code will export a Query to Excel using DoCmd.OutputTo:
DoCmd.OutputTo acOutputQuery, "Query1", acFormatXLSX, "c:tempExportedQuery.xls"
Or you can use the DoCmd.TransferSpreadsheet method instead:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Query1", "c:tempExportedQuery.xls", True
Note: This code exports to XLSX format. Instead you can update the arguments to export to a CSV or XLS file format instead (ex. acFormatXLSX to acFormatXLS).
Export Report to Excel
This line of code will export a Report to Excel using DoCmd.OutputTo:
DoCmd.OutputTo acOutputReport, "Report1", acFormatXLSX, "c:tempExportedReport.xls"
Or you can use the DoCmd.TransferSpreadsheet method instead:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Report1", "c:tempExportedReport.xls", True
Export Table to Excel
This line of code will export a Table to Excel using DoCmd.OutputTo:
DoCmd.OutputTo acOutputTable, "Table1", acFormatXLSX, "c:tempExportedTable.xls"
Or you can use the DoCmd.TransferSpreadsheet method instead:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Table1", "c:tempExportedTable.xls", True
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Export Form to Excel
This line of code will export a Form to Excel using DoCmd.OutputTo:
DoCmd.OutputTo acOutputForm, "Form1", acFormatXLSX, "c:tempExportedForm.xls"
Or you can use the DoCmd.TransferSpreadsheet method instead:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Form1", "c:tempExportedForm.xls", True
Export to Excel Functions
These one line commands work great to export to a new Excel file. However, they will not be able to export into an existing workbook. In the section below we introduce functions that allow you to append your export to an existing Excel file.
Below that, we’ve included some additional functions to export to new Excel files, including error handling and more.
Export to Existing Excel File
The above code examples work great to export Access objects to a new Excel file. However, they will not be able to export into an existing workbook.
To export Access objects to an existing Excel workbook we’ve created the following function:
Public Function AppendToExcel(strObjectType As String, strObjectName As String, strSheetName As String, strFileName As String)
Dim rst As DAO.Recordset
Dim ApXL As Excel.Application
Dim xlWBk As Excel.Workbook
Dim xlWSh As Excel.Worksheet
Dim intCount As Integer
Const xlToRight As Long = -4161
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Const xlContinuous As Long = 1
Select Case strObjectType
Case "Table", "Query"
Set rst = CurrentDb.OpenRecordset(strObjectName, dbOpenDynaset, dbSeeChanges)
Case "Form"
Set rst = Forms(strObjectName).RecordsetClone
Case "Report"
Set rst = CurrentDb.OpenRecordset(Reports(strObjectName).RecordSource, dbOpenDynaset, dbSeeChanges)
End Select
If rst.RecordCount = 0 Then
MsgBox "No records to be exported.", vbInformation, GetDBTitle
Else
On Error Resume Next
Set ApXL = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set ApXL = CreateObject("Excel.Application")
End If
Err.Clear
ApXL.Visible = False
Set xlWBk = ApXL.Workbooks.Open(strFileName)
Set xlWSh = xlWBk.Sheets.Add
xlWSh.Name = Left(strSheetName, 31)
xlWSh.Range("A1").Select
Do Until intCount = rst.fields.Count
ApXL.ActiveCell = rst.fields(intCount).Name
ApXL.ActiveCell.Offset(0, 1).Select
intCount = intCount + 1
Loop
rst.MoveFirst
xlWSh.Range("A2").CopyFromRecordset rst
With ApXL
.Range("A1").Select
.Range(.Selection, .Selection.End(xlToRight)).Select
.Selection.Interior.Pattern = xlSolid
.Selection.Interior.PatternColorIndex = xlAutomatic
.Selection.Interior.TintAndShade = -0.25
.Selection.Interior.PatternTintAndShade = 0
.Selection.Borders.LineStyle = xlNone
.Selection.AutoFilter
.Cells.EntireColumn.AutoFit
.Cells.EntireRow.AutoFit
.Range("B2").Select
.ActiveWindow.FreezePanes = True
.ActiveSheet.Cells.Select
.ActiveSheet.Cells.WrapText = False
.ActiveSheet.Cells.EntireColumn.AutoFit
xlWSh.Range("A1").Select
.Visible = True
End With
'xlWB.Close True
'Set xlWB = Nothing
'ApXL.Quit
'Set ApXL = Nothing
End If
End Function
You can use the function like this:
Private Sub AppendToExcel_Example()
Call VBA_Access_ImportExport.ExportToExcel("Table", "Table1", "VBASheet", "C:TempTest.xlsx")
End Sub
Notice you are asked to define:
- What to Output? Table, Report, Query, or Form
- Object Name
- Output Sheet Name
- Output File Path and Name.
VBA Programming | Code Generator does work for you!
Export SQL Query to Excel
Instead you can export an SQL query to Excel using a similar function:
Public Function AppendToExcelSQLStatemet(strsql As String, strSheetName As String, strFileName As String)
Dim strQueryName As String
Dim ApXL As Excel.Application
Dim xlWBk As Excel.Workbook
Dim xlWSh As Excel.Worksheet
Dim intCount As Integer
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Const xlVAlignCenter = -4108
Const xlContinuous As Long = 1
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
strQueryName = "tmpQueryToExportToExcel"
If ObjectExists("Query", strQueryName) Then
CurrentDb.QueryDefs.Delete strQueryName
End If
Set qdf = CurrentDb.CreateQueryDef(strQueryName, strsql)
Set rst = CurrentDb.OpenRecordset(strQueryName, dbOpenDynaset)
If rst.RecordCount = 0 Then
MsgBox "No records to be exported.", vbInformation, GetDBTitle
Else
On Error Resume Next
Set ApXL = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set ApXL = CreateObject("Excel.Application")
End If
Err.Clear
ApXL.Visible = False
Set xlWBk = ApXL.Workbooks.Open(strFileName)
Set xlWSh = xlWBk.Sheets.Add
xlWSh.Name = Left(strSheetName, 31)
xlWSh.Range("A1").Select
Do Until intCount = rst.fields.Count
ApXL.ActiveCell = rst.fields(intCount).Name
ApXL.ActiveCell.Offset(0, 1).Select
intCount = intCount + 1
Loop
rst.MoveFirst
xlWSh.Range("A2").CopyFromRecordset rst
With ApXL
.Range("A1").Select
.Range(.Selection, .Selection.End(xlToRight)).Select
.Selection.Interior.Pattern = xlSolid
.Selection.Interior.PatternColorIndex = xlAutomatic
.Selection.Interior.TintAndShade = -0.25
.Selection.Interior.PatternTintAndShade = 0
.Selection.Borders.LineStyle = xlNone
.Selection.AutoFilter
.Cells.EntireColumn.AutoFit
.Cells.EntireRow.AutoFit
.Range("B2").Select
.ActiveWindow.FreezePanes = True
.ActiveSheet.Cells.Select
.ActiveSheet.Cells.WrapText = False
.ActiveSheet.Cells.EntireColumn.AutoFit
xlWSh.Range("A1").Select
.Visible = True
End With
'xlWB.Close True
'Set xlWB = Nothing
'ApXL.Quit
'Set ApXL = Nothing
End If
End Function
Called like this:
Private Sub AppendToExcelSQLStatemet_Example()
Call VBA_Access_ImportExport.ExportToExcel("SELECT * FROM Table1", "VBASheet", "C:TempTest.xlsx")
End Sub
Where you are asked to input:
- SQL Query
- Output Sheet Name
- Output File Path and Name.
Function to Export to New Excel File
These functions allow you to export Access objects to a new Excel workbook. You might find them more useful than the simple single lines at the top of the document.
Public Function ExportToExcel(strObjectType As String, strObjectName As String, Optional strSheetName As String, Optional strFileName As String)
Dim rst As DAO.Recordset
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
Dim intCount As Integer
Const xlToRight As Long = -4161
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Const xlContinuous As Long = 1
On Error GoTo ExportToExcel_Err
DoCmd.Hourglass True
Select Case strObjectType
Case "Table", "Query"
Set rst = CurrentDb.OpenRecordset(strObjectName, dbOpenDynaset, dbSeeChanges)
Case "Form"
Set rst = Forms(strObjectName).RecordsetClone
Case "Report"
Set rst = CurrentDb.OpenRecordset(Reports(strObjectName).RecordSource, dbOpenDynaset, dbSeeChanges)
End Select
If rst.RecordCount = 0 Then
MsgBox "No records to be exported.", vbInformation, GetDBTitle
DoCmd.Hourglass False
Else
On Error Resume Next
Set ApXL = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set ApXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo ExportToExcel_Err
Set xlWBk = ApXL.Workbooks.Add
ApXL.Visible = False
Set xlWSh = xlWBk.Worksheets("Sheet1")
If Len(strSheetName) > 0 Then
xlWSh.Name = Left(strSheetName, 31)
End If
xlWSh.Range("A1").Select
Do Until intCount = rst.fields.Count
ApXL.ActiveCell = rst.fields(intCount).Name
ApXL.ActiveCell.Offset(0, 1).Select
intCount = intCount + 1
Loop
rst.MoveFirst
xlWSh.Range("A2").CopyFromRecordset rst
With ApXL
.Range("A1").Select
.Range(.Selection, .Selection.End(xlToRight)).Select
.Selection.Interior.Pattern = xlSolid
.Selection.Interior.PatternColorIndex = xlAutomatic
.Selection.Interior.TintAndShade = -0.25
.Selection.Interior.PatternTintAndShade = 0
.Selection.Borders.LineStyle = xlNone
.Selection.AutoFilter
.Cells.EntireColumn.AutoFit
.Cells.EntireRow.AutoFit
.Range("B2").Select
.ActiveWindow.FreezePanes = True
.ActiveSheet.Cells.Select
.ActiveSheet.Cells.WrapText = False
.ActiveSheet.Cells.EntireColumn.AutoFit
xlWSh.Range("A1").Select
.Visible = True
End With
retry:
If FileExists(strFileName) Then
Kill strFileName
End If
If strFileName <> "" Then
xlWBk.SaveAs strFileName, FileFormat:=56
End If
rst.Close
Set rst = Nothing
DoCmd.Hourglass False
End If
ExportToExcel_Exit:
DoCmd.Hourglass False
Exit Function
ExportToExcel_Err:
DoCmd.SetWarnings True
MsgBox Err.Description, vbExclamation, Err.Number
DoCmd.Hourglass False
Resume ExportToExcel_Exit
End Function
The function can be called like this:
Private Sub ExportToExcel_Example()
Call VBA_Access_ImportExport.ExportToExcel("Table", "Table1", "VBASheet")
End Sub
importing excel into access, step by step
Introduction
In Microsoft Access, it is possible to accomplish most things in at least a couple of different ways, and importing Excel data into Access is no different. So, in this article, we show you how to import Excel into Access using the VBA language. For instance, we will be using the Excel Object Model. By learning this approach, you will learn insights regarding Microsoft Access, Microsoft Excel object model integration and, at the same time, we will present some ideas regarding DML (data manipulation language) operations against Access tables using SQL.
Advantages of importing Excel into Access Using Excel Object Model
Other advantages of using the Excel object model are:
- Full access to each row / column value that allows complex validations, lookup processes and data cleanup
- Data type conversion
- Access to all Excel object model functions if required
Let’s Start Importing Excel Into Access using VBA
To create the final outcome the reader will need
- A test excel file
- A Microsoft Access database with one table and a single form with a button
The first step will be to obtain some Excel sample data to test the load process. Once generating several lines of dummy data is a tedious process a simpler approach is to download some sample test data, I found this sample file
http://www.sample-videos.com/xls/Sample-Spreadsheet-10000-rows.xls
In the same page the reader will find other smaller and bigger files. The selected file layout is as follows
There are ten columns present without column headings.
In this example we will import columns A, B and G into the destination database table.
Let’s start …
After creating an empty Microsoft Access database, the user should create an empty table with the layout presented below
The table field ItemId will be mapped to column A, the field Description will be mapped to column B and the field Price to column G. The reader should pay attention to the field price underlying data type. Once source data can have decimal numbers the destination field should be able to accommodate them (remember when working with SQL the decimal separator is the dot). The first field is simply an integer sequence and the second one a description text string (more notes on this later on).
Once the table is properly created the next step will be the creation of a simple form with a button to trigger the process. Assuming the reader already has some Microsoft Access experience the final form should be similar to
Change the button property caption to Import Excel and the button name to cmdImportExcel (as mentioned in previous tutorial, naming conventions are always a good practice). Click the save button and name the form as frmImportExcel.
To provide some user friendly features the created button will call a file picker control dialog, this way the user will be able to select the source file from the hard-drive picking it from any location.
Right click on the insert button, choose build event and then code builder. The Visual Basic editor should open
As a side not let’s force explicit variable declaration in the code so each required variable is declared using its proper data type and no machine resources are allocated in vain. In the top of the code (bellow Option Compare Database) simply add
Option Explicit
From now on all required variables will require a proper declaration.
Before implementing the code let’s explain the underlying sequence logic:
- The user will see a file picker dialog opening
- The user will be able to pick the excel file
- If an Excel file was picked its path will be assigned to a variable
- The path stored in that variable will be used to open the Excel in background and load all rows into the Access table
Implementing the file dialog control
To use the file dialog control, we must provide a reference to the Microsoft Office XX Object Library (will depend on the office version installed). To do that access the Tools -> References menu in the VBA editor.
Navigate down using the scroll bar and choose the installed Office object library installed.
From now on all objects and methods provided by it are available to use.
Let’s add the file dialog picker underlying code…
In the VBA editor, inside cmdImportExcel_Click() event put the following code. The code is highly commented so the reader understands what each line is doing.
Private Sub cmdImportExcel_Click()
On Error GoTo cmdImportExcel_Click_err:
Dim fdObj As Office.FileDialog ‘declares variable fdObj
Dim varfile As Variant ‘variant type variable that will store the selected file path
Set fdObj = Application.FileDialog(msoFileDialogFilePicker) ‘instantiates the variable creating a filepicker object using late binding
With fdObj ‘using the with statement we will be working with fdObj by default
‘does not allow selecting more than one file
.allowmultiselect = False
‘clears the file dialog file type existing filters
.Filters.Clear
‘this file dialog will only allow the selection of xlsx files
.Filters.Add “Excel 2007+”, “*.xlsx”
‘optional, set the file dialog title
.Title = “Please select the excel file to import …”
.Show
If .SelectedItems.Count = 1 Then ‘a file was selected
Call MsgBox(“The selected file was: ” & .SelectedItems(1)) ‘for now we will test the file picking by sending the file path to a message box on screen
Else ‘no file was selected
Call MsgBox(“No file was selected.”)
End If
End With
Exit Sub
cmdImportExcel_Click_err:
Select Case Err.Number
Case Else
Call MsgBox(Err.Number & ” – ” & Err.Description, vbCritical + vbOKOnly, “System Error …”)
End Select
End Sub
Now let’s test the code and check how it works. First let’s visualize the form view by clicking as presented in the next picture
Then the form will be presented
The reader should now press the Import Excel button and a file picker dialog will be presented
Next please select the downloaded file, hit the open button and the outcome should be similar to the one bellow only showing a proper path
If this is the outcome, everything is working as expected and the file picking component is working already. Next we will see how to include the Excel object model into the Microsoft Access solution. The reader will have to include the proper reference to the Excel object model. Once again, access the Tools -> References menu in the VBA editor.
And mark the check box reference to the Excel application
From now on all Excel object methods and properties will be available once an Excel variable is created inside the Microsoft Access VBA code. This technique is called early binding, data types are known in advance but checking these references is not mandatory. If those references are not set a late binding technique is being used but it will make development more difficult as the code editor intellisense will not show the properties and methods, deep documentation reading will be required. A common approach is to use the reference while developing and removing it when finished, the unknown constants must then be replaced by their corresponding integer values. We will not get into much more detail but it is important to be aware these references are not mandatory, they just make life easier.
Once the reference to Excel is created we can declare variables types defined there. We will need to declare three variables
- xlApp – will be a reference to a hidden Excel application
- xlWb – will be a reference to the workbook opened as a result of opening the file to import
- xlWs – will be a reference to the worksheet having data to import
The steps involved in the load process can be described as follows
- Delete existing data in destination table
- Loop through all excel lines running an insert statement per line until the last line is reached
- The loop process will stop when it does not find any more data in the column A
The required code for the entire process is the following. We will add extensive comments on all lines, please check them bellow in green
Private Sub cmdImportExcel_Click()
On Error GoTo cmdImportExcel_Click_err:
Dim fdObj As Office.FileDialog ‘declares variable fdObj
Dim varfile As Variant ‘variant type variable that will store the selected file path
Set fdObj = Application.FileDialog(msoFileDialogFilePicker) ‘instantiates the variable creating a filepicker object using early binding
With fdObj ‘using the with statement we will be working with fdObj by default
‘does not allow selecting more than one file
.allowmultiselect = False
‘clears the file dialog file type existing filters
.Filters.Clear
‘this file dialog will only allow the selection of excel files, this is achieved handling the Filters collection
.Filters.Add “Excel 2003”, “*.xls”
.Filters.Add “Excel 2007+”, “*.xlsx”
‘optional set the file dialog title
.Title = “Please select the excel file to import …”
.Show
If .SelectedItems.Count = 1 Then ‘a file was selected so data can be imported from Excel from this point the loop import process will run
‘variables declaration
Dim xlApp As Excel.Application ‘the excel application
Dim xlWb As Excel.Workbook ‘the excel workbook reference that will point to the opened workbook
Dim xlWs As Excel.Worksheet ‘the excel worksheet with data
Dim intLine As Long ‘the line counter
Dim strSqlDml As String ‘string variable that stores the executed SQL statements
Dim strColumnBcleaned As String ‘string variable that stores values from column B after replacing single quotes by four single quotes
‘remember the quote is the string delimiter in SQL so it needs to be escaped
Dim strColumnGcleaned As String ‘string variable that stores values from column G cleaned, the clean step replaces commas by dots as
‘the decimal separator in SQL is the dot
varfile = .SelectedItems(1) ‘picking the selected file full path
clean the existing table
CurrentDb.Execute “DELETE * FROM tblExcelImport”, dbFailOnError
‘instantiate the Excel application, creating the Excel application in memory, the excel Accplication will be visible so the user is able to see the loop iterating through Excel rows but usually it is hidden and only visible if indeed required
Set xlApp = New Excel.Application
xlApp.Visible = True
‘opening the picked file by calling the Excel workbooks collection open method, it receives the file location as parameter and returns a reference for the opened file
Set xlWb = xlApp.Workbooks.Open(varfile)
‘seting the worksheet to the first one within the available, as it is the one having data to be imported
Set xlWs = xlWb.Worksheets(1)
‘default counter initial value/line, this means we start iterating in line one
intLine = 1
Do
‘the next two lines replace single quotes in column B value and commas by dots as decimal separator in column G
strColumnBcleaned = Replace(xlWs.Cells(intLine, 2).Value2, “‘”, “”””)
strColumnGcleaned = Replace(xlWs.Cells(intLine, 7).Value2, “‘”, “”””)
‘the next line creates a SQL insert statement using the previous obtained cleaned variables and the value for column A
The insert statement must have the sequence present in the destination table and is obtained by concatenating values per each line presented in the Excel file while iterating
strSqlDml = “INSERT INTO tblExcelImport VALUES(” & xlWs.Cells(intLine, 1).Value2 & “, ‘” & strColumnBcleaned & “‘, ” & strColumnGcleaned & “)”
‘executes the insert statement against the database, the dbFailOnError is an optional value that will make the Execute process return an error if the SQL was not properly executed
CurrentDb.Execute strSqlDml, dbFailOnError
‘the next line only puts the selected cell in Excel in the actual line position, this is not required and will even make the process slower, it is just present here so the reader can see things running
xlWs.Cells(intLine, 1).Select
intLine = intLine + 1
Loop Until IsEmpty(xlWs.Cells(intLine, 1)) ‘stopping criteria, when values in column A stop the loop will stop, please note in cells collection the first index is the row and the second one the column so we are making row changing. Once the loop stops the steps after close the open workbook, quit excel and clean the memory references to the created objects
xlWb.Close False
xlApp.Quit
Set xlApp = Nothing
Set xlWb = Nothing
Set xlWs = Nothing
‘the next step opens the loaded table so the user can see imported data
DoCmd.OpenTable “tblExcelImport”, acViewNormal, acEdit
‘this branch only happens if no file was selected
Else ‘no file was selected
Call MsgBox(“No file was selected.”)
End If
End With
Exit Sub
cmdImportExcel_Click_err:
Select Case Err.Number
Case Else
Call MsgBox(Err.Number & ” – ” & Err.Description, vbCritical + vbOKOnly, “System Error …”)
End Select
End Sub
As mentioned before, this is not the only approach to import Excel data, it is possible to create linked tables and, to import data into Microsoft Access, the reader should also consider the DoCmd.TransferDatabase method as well. Linked tables can make use of connectivity drivers so they may not point only to databases, it is even possible to create a linked table to a text file.
Some relevant examples related to the IN clause can be found over here
https://msdn.microsoft.com/en-us/library/bb177907(v=office.12).aspx
To run a query in Access pulling data from an Excel file a similar solution to the following one can be used
SELECT CustomerID, CompanyName
FROM [Customers$]
IN “c:documentsxldata.xls” “EXCEL 5.0;”
WHERE CustomerID Like “A*”
ORDER BY CustomerID;
Also, when dealing with SQL statements built dynamically it is very important to handle possible null values, replacing them by default values or even forcing the null value insert.
If a value can be null the variable needs to be of type Variant to store it and then use it in the built insert statement.
Conclusion
Thanks for reading about how to import excel into Access. Leave a comment if you have any questions on how to import excel into access.
Looking for a job?
Find A Job via Jooble