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.
Загрузить PDF
Загрузить PDF
Access – это реляционная система управления базами данных, в которую можно импортировать одну или несколько таблиц Excel и согласовать их однородные элементы. Более того, при помощи Access можно собрать и проанализировать большое количество данных, так как один файл Access включает несколько таблиц Excel. Но для начала необходимо импортировать данные из Excel в Access; это можно сделать, выполнив несколько основных действий.
-
1
На компьютере запустите Excel и Access. Необходимо купить и скачать пакет Microsoft Office, который содержит и Excel,[1]
и Access. Это можно сделать на официальном сайте компании Microsoft.- Установив пакет Microsoft Office, в Windows нажмите «Пуск» – «Все программы».[2]
- Нажмите «Microsoft Office» и в открывшемся меню выберите «Access» (или «Excel»). Скорее всего, у вас уже есть таблица Excel, которую вы скачали или получили по электронной почте. При помощи программы Excel вы сможете открыть такую таблицу.
- Установив пакет Microsoft Office, в Windows нажмите «Пуск» – «Все программы».[2]
-
2
Перед импортом данных в Access обработайте таблицу Excel. Это сильно облегчит задачу по переносу данных из Excel в Access. Суть в том, что в разных таблицах определенные данные должны иметь один формат.[3]
- Для начала удостоверьтесь, что первая строка каждой импортируемой таблицы содержит названия (заголовки) столбцов – названия должны ясно характеризовать данные, занесенные в столбцы.[4]
Например, если столбец содержит фамилии людей, назовите его «Фамилии». Давайте точные названия, чтобы облегчить процесс согласования заголовков столбцов в разных таблицах. - В Access вы можете согласовать однородные элементы в двух и более таблицах Excel. Например, у вас есть таблица Excel с данными по заработной плате, которая содержит ФИО (фамилия, имя, отчество), адреса и суммы заработной платы. Допустим, вы хотите сопоставить эту таблицу с другой таблицей, включающей данные о пожертвованиях на некий проект (ФИО, адреса и суммы пожертвований). В Access вы можете согласовать заголовки столбцов в разных таблицах. В нашем примере согласуйте названия столбцов с фамилиями, чтобы выяснить, какие люди присутствуют в обеих таблицах.
- Просмотрите каждую таблицу Excel и убедитесь, что данные внесены в одном формате; в противном случае обработайте таблицу так, чтобы привести данные к одному формату.[5]
Такой подход к формату данных отражает слово «реляционная» (от relation – зависимость, связь) в описании Access. Например, если в зарплатной таблице в столбце «ФИО» введены фамилии, имена и отчества, а в таблице о пожертвованиях в столбце «ФИО» – только фамилии и имена, то Access не считает данные столбцы однородными (то есть не сможет согласовать их). Поэтому одинаковыми должны быть как названия столбцов, так и формат данных, которые содержатся в этих столбцах.
- Для начала удостоверьтесь, что первая строка каждой импортируемой таблицы содержит названия (заголовки) столбцов – названия должны ясно характеризовать данные, занесенные в столбцы.[4]
-
3
Разделите данные в столбцах таблицы Excel. Для того чтобы сделать элементы таблицы Excel однородными (для их импорта в Access), разделите информацию в соответствующих столбцах.[6]
- Например, вы можете поместить фамилию в один столбец, имя – во второй, а отчество – в третий. Аналогичным образом поступите с соответствующим столбцом во второй таблице. Теперь в Access вы сможете согласовать, например, фамилии из одной таблицы с фамилиями из другой и найти людей, которые присутствуют в обеих таблицах.
- Для разделения данных в столбце Excel выделите нужный столбец. В панели инструментов нажмите «Данные». Затем нажмите «Текст по столбцам». Рекомендуется выбрать опцию «С разделителями». Затем нажмите «Далее».
-
4
Для разделения данных, расположенных в одном столбце, следуйте подсказкам Мастера текстов. Выполните следующие действия:
- Выберите символ-разделитель между данными. Помните, что информация, занесенная в ячейку, разделяется каким-то символом. Как правило, таким символом-разделителем является пробел, запятая или точка с запятой. В подавляющем большинстве случаев информация разделяется пробелом. Например, в ячейку занесена следующая информация: Иванов Иван Иванович. Здесь Фамилия отделена от имени пробелом, а имя отделено от отчества также пробелом. В этом случае в окне Мастера текстов выберите опцию «Пробел».
- Нажмите «Далее». Затем нажмите «Готово». Столбец с ячейкой «Иванов Иван Иванович» разделится на три столбца. Теперь вы можете присвоить имя каждому из трех новых столбцов, то есть назвать их как «Фамилия», «Имя», «Отчество». Перед разделением информации справа от разделяемого столбца вставьте несколько пустых столбцов, чтобы Excel занес в них разделенные данные (а не в уже заполненные столбцы с другими данными).
Реклама
-
1
Запустите Access. Для этого нажмите «Пуск» – «Microsoft Office» – «Microsoft Access». Для импорта данных из Excel создайте новую базу данных Access.
- Для создания базы данных в окне программы Access нажмите «Новая база данных».
- Если хотите, присвойте созданной базе данных имя. Затем нажмите «Создать».
-
2
Импортируйте таблицу Excel в Access. Теперь вы можете импортировать данные из одной или нескольких таблиц Excel в Access.
- На панели инструментов (в окне программы Access) нажмите «Внешние данные».[7]
В некоторых версиях Access на панели инструментов нажмите «Файл» – «Внешние данные».[8]
- В разделе «Имя файла» нажмите «Обзор», чтобы найти нужную таблицу Excel.
- Поставьте флажок у опции «Импортировать исходные данные в новую таблицу в текущей базе данных» (эта опция активирована по умолчанию).
- Найдя нужную таблицу, щелкните по ней. Затем нажмите «OK». Откроется мастер импорта данных из Excel в Access.
Реклама
- На панели инструментов (в окне программы Access) нажмите «Внешние данные».[7]
-
1
Выполните указания мастера импорта данных. Это необходимо сделать для завершения процесса импорта таблицы Excel в Access.
- Выберите лист в таблице Excel, данные которого вы хотите импортировать в Access. Порой это очень легко, потому что таблица содержит всего один лист. Но иногда одна таблица Excel включает множество листов, вкладки которых отображаются в нижней части окна программы Excel; в этом случае нужно указать определенный лист. Затем нажмите «Далее».
- Отобразится окно с вопросом, содержит ли первая строка таблицы заголовки столбцов. Здесь имеются в виду названия, характеризующие данные в каждом столбце (например, фамилия, адрес, сумма заработной платы и так далее). Прекрасно, если до этого вы обработали таблицу Excel так, что первая строка содержит строго определенные названия столбцов; в этом случае отметьте опцию, что первая строка содержит заголовки столбцов. Затем нажмите «Далее».
- Если в первой строке заголовков столбцов нет, в открывшемся окне отобразится вопрос о том, хотите ли вы присвоить имена «полям» (в Access под «полями» понимаются заголовки столбцов). Если до этого вы не вводили названия столбцов, сделайте это сейчас.
-
2
Завершите импорт данных. Вам осталось выполнить всего несколько действий. В открывшемся окне определите первичный ключ (если хотите).
- Вы можете, но не обязаны, делать это. Первичный ключ – это уникальный номер, присваиваемый каждой строке с данными; это может пригодиться при сортировке данных. Затем нажмите «Далее».[9]
- В последнем окне отобразится имя по умолчанию. Вы можете переименовать таблицу Excel (по завершении импорта она отобразится в виде таблицы Access на левой стороне экрана).
- Нажмите «Импорт», а затем нажмите «Закрыть». Таблица отобразится на левой стороне экрана; это значит, что она полностью импортирована в Access.
- Если вы хотите согласовать несколько баз данных, проделайте вышеописанные действия для импорта одной или нескольких дополнительных таблиц Excel. Теперь вы можете приступить к согласованию данных в Access.
Реклама
- Вы можете, но не обязаны, делать это. Первичный ключ – это уникальный номер, присваиваемый каждой строке с данными; это может пригодиться при сортировке данных. Затем нажмите «Далее».[9]
Предупреждения
- Имейте в виду, что если версия Excel, в которой была создана таблица, отличается от версии Access, вы можете столкнуться с проблемами при импорте данных.
- Повторим еще раз: перед импортом данных обработайте таблицу Excel. То есть обратите внимание на формат данных, с которыми вы собираетесь работать.
- Сделайте копию исходной таблицы, чтобы в крайнем случае вы смогли импортировать данные еще раз.
- В Access можно импортировать не более 255 столбцов.[10]
Реклама
Об этой статье
Эту страницу просматривали 45 293 раза.
Была ли эта статья полезной?
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
Applicable to: Office 2019/2016/365
Here’s a question from Mike:
“I know how to create Access forms and capture user input into a database table, but as i have already gathered there a way to automatically import data from an Excel workbook into an Access database table instead”?
Good question, Thanks. Yes, you can automatically import data from an Excel worksheet into new and existing Access tables so that later you can run queries and data analyses against that data set. Read on for the step by step data acquisition instructions from Excel.
Create Access table from Excel
Important Note: Before attempting to import the Excel file content ensure that the file you are about to import contains data in tabular form with proper and descriptive headings. Also, might be a good idea to ensure that your spreadsheet doesn’t contain any duplicated rows.
- Open Microsoft Access.
- When prompted, either select an existing database or create a blank database.
- In Access 2016, go ahead and hit the External Data tab in the ribbon.
- Next, from the import & link Group, hit the Excel button.
- Alternatively, if you are using Access 2019, hit New Data Source>>From File and select Excel
- Next, go ahead and hit Browse to select the Excel file that will be imported into the table.
- Browse to your computer or shared location to find your Excel spreadsheet.
- Once done, hit Open.
- Next, you should specify how you would like to store the Excel data in your Access database.
- In this case, we want to go ahead and create a table and then insert the imported Excel data into it. Therefore, we’ll select import the source data into a new table in the current database and click OK.
- If your Excel spreadsheet has column headings, make sure to mark the First Row Contains.. check box; then hit Next.
- Then select each column to modify the field name and data type if needed.
- Hit Next.
- Now select if we need primary key option in your table.
- Check on Let Access add primary key to make access to add a column, use it as primary key or select choose my own primary key and add the primary key column.
- If we do not need primary key, check on No primary key.
- Your last step will be to define a meaningful name for the newly created table,.
- As an optional step, you might want to run a quick analysis to optimize your table. The analysis tool allows you to identify duplicates, compact the table for better performance etc’. If so, then go ahead and check I would like to analyze my table after importing the data and click Finish.
Note: So far, we learnt how to bring on data from Excel to Access. You might be as well interested in exporting your data from Access to Excel.
Import Excel to Access existing tables
Sometime your might need to append data that is stored in an Excel (either as a XLS or CSV file format) into an existing Access database table.
- If we need to insert the Excel spreadsheet data into the database which was created by us before, check on Append a copy of the records into the table.
- Hit Next.
- Remember, the column names of the table has to be same as the column names in the Excel sheet that is going to be imported.
- Hit Finish.
Hope it helps. This was just a simple data import tutorial for beginners. Readers looking at specific questions or solutions are advised to inquiry via the contact page.
We can use Microsoft Access to store a wide range of information for reporting and analysis. In this tutorial, we will learn how to Import Excel Data into a new or existing table in the Access database or link Excel Data to Access. When we import data, Access simply creates a copy of our source data, without making any changes to it.
Figure 1 – How to import excel into access
How to Import Excel Data into New table in the Access Database
- If we are using Access 2010 or 2013, we will go to the External Data Tab, and select the Excel option in the Import & Link group
- If we are using Access 2007, we will go to the External Data Tab, click on the Excel option in the Import Group
- If we are using the Access 2019, 2016 or Office 365, we will go to the External Data tab and select New Data Source in the Import & Link group. Next, we will select From File and then, Excel
Figure 2 – Importing access data into excel
- We will be directed to the External Data dialog box
Figure 3 – Import excel into access
- In the Get External Data dialog box, we will select the location of the file we want to import
Figure 4 – Import excel data into access
- We will mark “Import the source data into a new table in the current database” option
Figure 5 – Microsoft access import from excel
- In the Import Spreadsheet Wizard, we will mark “first Row contains Headings” and we will click Next.
Figure 6 – Import excel data into access
- Next, we can specify the format for each category.
Figure 7 – How to import excel data into access
- We will define our Primary Key, which is the unique signature to our table. We will let Access define this key for the sake of our tutorial.
Figure 8 – Import excel data into access
- We may choose to save Import steps
Figure 9 – How to import excel data into access
- We will enter our desired name for the Table
Figure 10 – Enter the desired name for our table
- Now, if we click on the My New Data Table, we will see our created table
Figure 11 – The New imported Table from Excel
How to import Excel Data into an existing table in the Access Database
We can add a different Excel worksheet to the already existing table in the Access Database. But we have to make sure that the column headings of the new table match with the existing table.
- We will go to the External Data Tab on the Ribbon
- In the Import and Link Group, we will go to From File and choose the Excel Button
- In the Get External Data dialog box, we will select the location of the file we want to import
- We will mark “Append a copy to the records to the table” option and specify the table we want to add our new data.
Figure 12 – Importing excel to access
- We will click Next
Figure 13 – Use Import Spreadsheet Wizard
- Our New Table will be added into the existing table in Access.
How to Link Excel Data to Access
We can link Excel Data to access so that we can make use of reporting and querying tools without storing a copy of our data inside the Access Database. When we link Data to Access, it will simply create a new table that contains links to the source cells. Whenever we modify the source cells, this will appear automatically in the linked table.
- In the Get External Data-Excel Spreadsheet dialog box, we will specify the location of the Excel sheet
Figure 14 – Link Excel Data to Access
- Next, we will mark “Link to a data source by creating a linked table”
Figure 15– Import Excel data into access
- We will specify that the first row contains headings
Figure 16 – Access Importing data from Excel
- We will name the Table
Figure 17 – Link Table to Access
- We will verify that we want to click Table by selecting OK.
Figure 18 – Excel Data into access
- When we click on My Linked Table, the result is the next figure
Figure 19 – New Excel Table from Access
Instant Connection to an Excel Expert
Most of the time, the problem you will need to solve will be more complex than a simple application of a formula or function. If you want to save hours of research and frustration, try our live Excelchat service! Our Excel Experts are available 24/7 to answer any Excel question you may have. We guarantee a connection within 30 seconds and a customized solution within 20 minutes.