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.
Содержание
- Import or link to data in an Excel workbook
- What do you want to do?
- Understand importing data from Excel
- Common scenarios for importing Excel data into Access
- If this is the first time you are importing data from Excel
- Import data from Excel
- Prepare the worksheet
- Prepare the destination database
- Start the import operation
- Use the Import Spreadsheet wizard
- Troubleshoot missing or incorrect values
Import or link to data in an Excel workbook
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Graphical elements, such as logos, charts, and pictures cannot be imported. Manually add them to the database after completing the import operation.
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.
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.
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.
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:
A Yes/No field displays -1 and 0 in Datasheet view after the import operation is completed. To fix this, after the import operation is complete, set the field’s Format property to Yes/No to display check boxes instead.
Long and medium dates might appear as short dates in Access. To fix this, open the destination table in Design view in Access and set the date field’s Format property to Long Date or Medium Date.
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:
The 1904 Date System (in which serial numbers range from 0 to 63,918), which correspond to the dates January 1, 1904 through December 31, 2078.
The 1900 Date System (in which serial numbers range from 1 to 65,380), which correspond to the dates January 1, 1900 through December 31, 2078.
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.
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:
Format the source columns.
Move the rows so that the first eight rows in each column do not contain values of different data types.
During the import operation, select the appropriate data type for each field. If the data type is incorrect, you might see null values or incorrect values in the entire column after the import operation has completed.
The preceding steps can help minimize the appearance of null values. The following table lists cases in which you will still see null values:
Источник
Загрузить 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 раза.
Была ли эта статья полезной?
Convert Excel to Access Database
Use this simple method to learn how to create Access database from Excel spreadsheet.
Programmers convert Excel to Access database for easy maintenance, minimize the load or as a database backup. This article is going to explain how to import Excel into Access without using any ADODB or connection string. This method is going to very simple.
Instead of creating a connection string and mapping to it in SQL query every time, we are going to just do an Export in single step by using the Microsoft Access Object Library. The process explained in this article will work better in Office 2007 and above.
How to Import Excel into Access Database?
Before using the Macro code, let’s see how import Excel into Access is done manually. We need a source file (Excel) and a target destination file (MDB). Assume there is a table as in below format in an Excel sheet. To convert this Excel to Access database, create a new MDB file.
- Open the MDB file & Choose “External Data” from Menu.
- Choose “Excel” from the list of sources (Access, Excel, Text, XML etc) Import Tab.
- Enter Excel file path in ‘File Name’ field in the Pop up window.
- Choose ‘Import to new Table’ or ‘Append’ or ‘Link’ as per your requirement.
- Click next, proceed with few more windows to choose the Sheet or view that has data.
- click Finish to complete importing Excel data to Access.
Now, the data from Excel will be imported to the current mdb database. Access will also ask confirmation whether you want to store the import steps, so that it will be easy to repeat the same steps in just one click.
Also Read: Different methods to Read Data from external Excel Workbook.
VBA to Export Excel to Access Database
To create Access database from Excel spreadsheet, Press Alt + F11 to view the VB Editor in Excel. Copy paste the below code, change the MDB File path and Table name as per your need.
- Include “Microsoft Access Object Library” from Tools -> References.
- Press F5 to execute this code and export data.
Option Explicit 'This Code is downloaded from Officetricks.com Public Sub Export_Excel_To_Access_MDB() Dim oDB As New Access.Application 'Create Object to Link to the Access Databse oDB.OpenCurrentDatabase "C:OfficeTricksExcel_To_Access.accdb", False 'Import data from Excel Spreadsheet to Access Database oDB.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "ExcelToAccess", ThisWorkbook.FullName, True 'Import only specific data range from Excel to Access oDB.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "ExcelToAccess", ThisWorkbook.FullName, True, "Sheet1$A1:E3" 'Export Data from Access to a Text File oDB.DoCmd.TransferText acExportDelim, TableName:="ExcelToAccess", Filename:=ThisWorkbook.Path & "ExportText.txt" 'Close Access Application and quit oDB.CloseCurrentDatabase oDB.Quit Set oDB = Nothing 'Process Completed MsgBox "Data Exported to Access DB" End Sub
The above code also explains how to (1) Export particular range from Excel to Access and (2) Export data from Access database to a Text file.
This page only explains about how to do a plain data transfer (i.,e directly convert Excel to Access). It does not include the explanations about how to build a SWL query, to insert, alter, and inquire data from Access. To do those processes, we have to make use of other options present in DoCmd collection of Access Application Object.
Introduction.
We can Import data from external data sources; from another Access database, dBase, FoxPro, Excel, and so on. We can Export data from Access into these Applications as well.
Following is a list of topics I have published earlier; either on importing, exporting, or working with external data sources from Microsoft Access:
- Exporting/Importing Data in Text format
- GetRows() Function and Exporting Data
- Import Objects with VB Code
- Adding Data Directly into External databases
- Link External Tables with VBA
- Linking with IBM AS400 Tables
Today, we will explore how to add a range of Excel cell data directly into Access Table, by running the VBA Code from within Excel.
The Algorithm of the program is as given below:
-
Create an Access Application Object and open it.
-
Open the target database within the Access Application.
-
Keep the Access Application window hidden.
-
Open the target table from the Database.
-
Take the count of Rows from one of the Excel data columns.
-
Open a repeating loop to write the excel data one row at a time, from the second row onwards.
-
Repeat the writing action till all the rows are transferred to the Access Table.
-
Close the table, and database, and quit the MS-Access Application.
The Excel VBA Code is Run by clicking a Command Button on the Excel Sheet. A sample image of the Excel Sheet with data and Command Button is given below:
Target Access Table Structure image is given below:
The Excel VBA Code
Sub Button1_Click() Dim objAcc As Object Dim recSet As Object Dim DataRow As Long, EndRow As Long On Error GoTo Button1_Click_Err 'Create Access Application Object Set objAcc = CreateObject("Access.Application") 'Open Database in Microsoft Access window objAcc.OpenCurrentDatabase "F:mdbsDatabase4XL.accdb", True 'Keep Access application window hidden objAcc.Visible = False 'Open Access Table to add records from Excel Set recSet = objAcc.CurrentDb.OpenRecordset("Table1") 'Take actual row counts of data for transfer EndRow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row With recSet For DataRow = 2 To EndRow .AddNew ![Desc] = Sheet1.Range("A" & DataRow).Value ![Qrtr1] = Sheet1.Cells.Range("B" & DataRow).Value ![Qrtr2] = Sheet1.Cells.Range("C" & DataRow).Value ![Qrtr3] = Sheet1.Cells.Range("D" & DataRow).Value ![Qrtr4] = Sheet1.Cells.Range("E" & DataRow).Value .Update Next End With recSet.Close objAcc.Quit Set objAcc = Nothing Button1_Click_Exit: Exit Sub Button1_Click_Err: MsgBox Err & " : " & Err.Description, , "Button1_Click()" Resume Button1_Click_Exit End Sub
Courtesy:
The non-functional raw VBA Code presented by a User at www.mrexcel.com/forum/microsoft-access, was modified by me to make it functional and was originally submitted there.
The first field of the table is an ID field with the data type AutoNumber. The ID field value is automatically generated when data is inserted into the other fields.
- Roundup Function
of Excel in MS-Access - Proper Function of
Excel in Microsoft Access - Appending Data from
Excel to Access - Writing Excel
Data Directly into Access - Printing MS-Access
Report from Excel - Copy Paste Data
From Excel to Access2007 - Microsoft Excel Power
in MS-Access - Rounding Function
MROUND of Excel - MS-Access Live Data in
Excel - Access Live Data in Excel-
2 - Opening Excel Database
Directly - Create Excel Word
File from Access
Share:
We can export the data from Microsoft Excel to Microsoft Access by using VBA. Below is the VBA code and process which you need to paste in the code module of the file.
1. Open Excel
2. Press ALT + F11
3. VBA Editor will OPEN
4. Click anywhere in the Project Window
5. Click on Insert
6. Click on Module
7. In the Code Window, Copy and Paste the below mentioned Code
Sub ADOFromExcelToAccess()
‘ exports data from the active worksheet to a table in an Access database
‘ this procedure must be edited before use
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
‘ connect to the Access database
Set cn = New ADODB.Connection
cn.Open «Provider=Microsoft.Jet.OLEDB.4.0; » & _
«Data Source=C:FolderNameDataBaseName.mdb;»
‘ open a recordset
Set rs = New ADODB.Recordset
rs.Open «TableName», cn, adOpenKeyset, adLockOptimistic, adCmdTable
‘ all records in a table
r = 3 ‘ the start row in the worksheet
Do While Len(Range(«A» & r).Formula) > 0
‘ repeat until first empty cell in column A
With rs
.AddNew ‘ create a new record
‘ add values to each field in the record
.Fields(«FieldName1») = Range(«A» & r).Value
.Fields(«FieldName2») = Range(«B» & r).Value
.Fields(«FieldNameN») = Range(«C» & r).Value
‘ add more fields if necessary…
.Update ‘ stores the new record
End With
r = r + 1 ‘ next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
8. Once this is pasted, go to the Excel file
9. Click on the VIEW Tab on the ribbon
10. Click on Macros
11. Click on View Macros
12. The Shortcut Key to View Macros is ALT + F8
13. A Window will popup
14. Select the Macro
15. Here the Macro is named as “ADOFromExcelToAccess”
16. Select the Macro “ADOFromExcelToAccess”
17. Click on Run
18. Click OK to close the Box
This is how we can Export data from Excel to Access by using VBA in Microsoft Excel.
There are many ways to do this. Let’s look at a couple of case studies.
Export data from Excel to Access (ADO)
If you want to export data to an Access table from an Excel worksheet, the macro example below shows how this can be done.
Sub ADOFromExcelToAccess()
' exports data from the active worksheet to a table in an Access database
' this procedure must be edited before use
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=C:FolderNameDataBaseName.mdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "TableName", cn, adOpenKeyset, adLockOptimistic, adCmdTable
' all records in a table
r = 3 ' the start row in the worksheet
Do While Len(Range("A" & r).Formula) > 0
' repeat until first empty cell in column A
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("FieldName1") = Range("A" & r).Value
.Fields("FieldName2") = Range("B" & r).Value
.Fields("FieldNameN") = Range("C" & r).Value
' add more fields if necessary...
.Update ' stores the new record
End With
r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Also . . .
Export data from Excel to Access (DAO)
If you want to export data to an Access table from an Excel worksheet, the macro example below illustrates another way to do this.
Sub DAOFromExcelToAccess()
' exports data from the active worksheet to a table in an Access database
' this procedure must be edited before use
Dim db As Database, rs As Recordset, r As Long
Set db = OpenDatabase("C:FolderNameDataBaseName.mdb")
' open the database
Set rs = db.OpenRecordset("TableName", dbOpenTable)
' get all records in a table
r = 3 ' the start row in the worksheet
Do While Len(Range("A" & r).Formula) > 0
' repeat until first empty cell in column A
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("FieldName1") = Range("A" & r).Value
.Fields("FieldName2") = Range("B" & r).Value
.Fields("FieldNameN") = Range("C" & r).Value
' add more fields if necessary...
.Update ' stores the new record
End With
r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing
End Sub
Also . . .
Browse to a single EXCEL File and Import Data from that EXCEL File via TransferSpreadsheet (VBA)
Here’s yet another way . . .
Sub TryThis()
Dim strPathFile As String
Dim strTable As String, strBrowseMsg As String
Dim strFilter As String, strInitialDirectory As String
Dim blnHasFieldNames As Boolean
' Change this next line to True if the first row in EXCEL worksheet
' has field names
blnHasFieldNames = False
strBrowseMsg = "Select the EXCEL file:"
' Change C:MyFolder to the path for the folder where the Browse
' window is to start (the initial directory). If you want to start in
' ACCESS' default folder, delete C:MyFolder from the code line,
' leaving an empty string as the value being set as the initial
' directory
strInitialDirectory = "C:MyFolder"
strFilter = ahtAddFilterItem(strFilter, "Excel Files (*.xls)", "*.xls")
strPathFile = ahtCommonFileOpenSave(InitialDir:=strInitialDirectory, _
Filter:=strFilter, OpenFile:=False, _
DialogTitle:=strBrowseMsg, _
Flags:=ahtOFN_HIDEREADONLY)
If strPathFile = "" Then
MsgBox "No file was selected.", vbOK, "No Selection"
Exit Sub
End If
' Replace tablename with the real name of the table into which
' the data are to be imported
strTable = "tablename"
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
' Uncomment out the next code step if you want to delete the
' EXCEL file after it's been imported
' Kill strPathFile
End Sub
- Remove From My Forums
-
Question
-
User2013552827 posted
I need to upload, import an excel file and export to Acess to manage the data, but I don’t know how. My Code is:
Imports System Imports System.Data Imports System.Data.OleDb Imports System.Web Imports System.Web.UI Imports System.Web.UI.WebControls Public Class Dados Inherits System.Web.UI.Page Protected dtgFiles As System.Web.UI.WebControls.DataGrid Protected lblSql1 As System.Web.UI.WebControls.Label Public lblMessage As Label Public WithEvents btnUpload As Button Public WithEvents btnCarrega As Button Public filUpload As Object Private Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click Try If Not IsNothing(filUpload.PostedFile) Then Dim infoarquivo As New IO.FileInfo(filUpload.PostedFile.FileName) Dim strCaminho As String = "D:\Dados\" & infoarquivo.Name filUpload.PostedFile.SaveAs(strCaminho) Me.lblMessage.Text = "Arquivo enviado com sucesso!" Else Me.lblMessage.Text = "Selecione um arquivo!" End If Catch ex As Exception Me.lblMessage.Text = "Há erros! " & ex.Message End Try End Sub Private Sub btnCarrega_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCarrega.Click Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;" _ & "Data Source=D:\Dados\Archieve.xlsx;" _ & "Extended Properties=""Excel 12.0 Xml; IMEX=1; HDR=YES;""" 'HDR Pula Primeira lina do Excel Try Catch ex As Exception Me.lblMessage.Text = "Erro na conexão com a planilha. " & ex.Message End Try 'Primeiro DataGrid - vou exibir todos os dados da planilha Dim objConn As New OleDbConnection(strConn) Dim strSql As String = "SELECT * FROM [plan1$]" ' Previamente definido no arquivo Excel 'lblSql1.Text = strSql Dim objCmd As New OleDbCommand(strSql, objConn) Try 'abre a conexão com a fonte de dados e executa a consulta SQL para retornar os dados e vinculando-os ao datagrid1 objConn.Open() dtgFiles.DataSource = objCmd.ExecuteReader() dtgFiles.DataBind() Catch exc As Exception Response.Write(exc.ToString()) Finally objConn.Close() End Try End Sub End Class
This code upload, read excel file and show as datagrip. Any one could help me to put the data in one Access DB?
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.
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