Accessing access database from excel

Note: Microsoft Access doesn’t support importing Excel data with an applied sensitivity label. As a workaround, you can remove the label before importing and then re-apply the label after importing. For more information, see Apply sensitivity labels to your files and email in Office.

You can bring the data from an Excel workbook into Access databases in many ways. You can copy data from an open worksheet and paste it into an Access datasheet, import a worksheet into a new or existing table, or link to a worksheet from an Access database.

This topic explains in detail how to import or link to Excel data from Access desktop databases.

What do you want to do?

  • Understand importing data from Excel

  • Import data from Excel

  • Troubleshoot missing or incorrect values

  • Link to data in Excel

  • Troubleshoot #Num! and other incorrect values in a linked table

Understand importing data from Excel

If your goal is to store some or all of your data from one or more Excel worksheets in Access, you should import the contents of the worksheet into a new or existing Access database. When you import data, Access creates a copy of the data in a new or existing table without altering the source Excel worksheet.

Common scenarios for importing Excel data into Access

  • You are a long-time user of Excel but, going forward, you want to use Access to work with this data. You want to move the data in your Excel worksheets into one or more new Access databases.

  • Your department or workgroup uses Access, but you occasionally receive data in Excel format that must be merged with your Access databases. You want to import these Excel worksheets into your database as you receive them.

  • You use Access to manage your data, but the weekly reports you receive from the rest of your team are Excel workbooks. You would like to streamline the import process to ensure that data is imported every week at a specific time into your database.

If this is the first time you are importing data from Excel

  • There is no way to save an Excel workbook as an Access database. Excel does not provide functionality to create an Access database from Excel data.

  • When you open an Excel workbook in Access (in the File Open dialog box, change the Files of Type list box to Microsoft Office Excel Files and select the file you want), Access creates a link to the workbook instead of importing its data. Linking to a workbook is fundamentally different from importing a worksheet into a database. For more information about linking, see the section Link to data in Excel, later in this article.

Import data from Excel

The steps in this section explain how to prepare for and run an import operation, and how to save the import settings as a specification for later reuse. As you proceed, remember that you can import data from only one worksheet at a time. You cannot import all the data from a whole workbook at the same time.

Prepare the worksheet

  1. 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)

    1. Switch to Excel and open the worksheet that has data that you want to import.

    2. Select the range of cells that contain the data that you want to import.

    3. Right-click within the selected range and then click Name a Range or Define Name.

    4. 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.

  2. Review the source data and take action as described in this table.

    Element

    Description

    Number of columns

    The number of source columns that you want to import cannot exceed 255, because Access does not support more than 255 fields in a table.

    Skipping columns and rows

    It is a good practice to include only the rows and columns that you want to import in the source worksheet or named range.

    Rows    You cannot filter or skip rows during the import operation.

    Columns    You cannot skip columns during the operation if you choose to add the data to an existing table.

    Tabular format

    Ensure that the cells are in tabular format. If the worksheet or named range includes merged cells, the contents of the cell are placed in the field that corresponds to the leftmost column, and the other fields are left blank.

    Blank columns, rows, and cells

    Delete all unnecessary blank columns and blank rows in the worksheet or range. If the worksheet or range contains blank cells, try to add the missing data. If you are planning to append the records to an existing table, ensure that the corresponding field in the table accepts null (missing or unknown) values. A field will accept null values if its Required field property is set to No and its ValidationRule property setting doesn’t prevent null values.

    Error values

    If one or more cells in the worksheet or range contain error values, such as #NUM and #DIV, correct them before you start the import operation. If a source worksheet or range contains error values, Access places a null value in the corresponding fields in the table. For more information about ways to correct those errors, see the section Troubleshoot missing or incorrect values, later in this article.

    Data type

    To avoid errors during importing, ensure that each source column contains the same type of data in every row. Access scans the first eight source rows to determine the data type of the fields in the table. We highly recommend that you ensure that the first eight source rows do not mix values of different data types in any of the columns. Otherwise, Access might not assign the correct data type to the column.

    Also, it is a good practice to format each source column in Excel and assign a specific data format to each column before you start the import operation. Formatting is highly recommended if a column includes values of different data types. For example, the FlightNo column in a worksheet might contain numeric and text values, such as 871, AA90, and 171. To avoid missing or incorrect values, do the following:

    1. Right-click the column header and then click Format Cells.

    2. On the Number tab, under Category, select a format. For the FlightNo column, you would probably choose Text.

    3. Click OK.

    If the source columns are formatted, but still contain mixed values in the rows following the eighth row, the import operation might still skip values or convert values incorrectly. For troubleshooting information, see the section Troubleshoot missing or incorrect values.

    First row

    If the first row in the worksheet or named range contains the names of the columns, you can specify that Access treat the data in the first row as field names during the import operation. If your source worksheet or range doesn’t include the names, it is a good idea to add them to the source before you start the import operation.

    Note: If you plan to append the data to an existing table, ensure that the name of each column exactly matches the name of the corresponding field. If the name of a column is different from the name of the corresponding field in the table, the import operation will fail. To see the names of the fields, open the table in Design view in Access.

  3. 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

  1. Open the Access database where the imported data will be stored. Ensure that the database is not read-only, and that you have permissions to make changes to the database.

    -or-

    If you don’t want to store the data in any of your existing databases, create a blank database. To do so:

    Click the File tab, click New, and then click Blank Database.

  2. 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

  1. 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.

  2. In the Get External Data — Excel Spreadsheet dialog box, in the File name box, specify the name of the Excel file that contains the data that you want to import.

    -or-

    Click Browse and use the File Open dialog box to locate the file that you want to import.

  3. 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.

  4. Click OK.

    The Import Spreadsheet Wizard starts, and leads you through the import process. Go to the next set of steps.

Use the Import Spreadsheet wizard

  1. On the first page of the wizard, select the worksheet that contains the data that you want to import, and then click Next.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. Click Yes to save the details of the operation for future use. Saving the details helps you repeat the operation at a later time without having to step through the wizard each time.

See Save the details of an import or export operation as a specification to learn how to save your save your specification details.

See Run a saved import or export specification to learn how to run your saved import or link specifications.

See Schedule an import or export specification to learn how to schedule import and link tasks to run at specific times.

Troubleshoot missing or incorrect values

If you receive the message An error occurred trying to import file, the import operation completely failed. Conversely, if the import operation displays a dialog box that prompts you to save the details of the operation, the operation was able to import all or some of the data. The status message also mentions the name of the error log table that contains the description of any errors that occurred during the import operation.

Important: Even if the status message indicates a completely successful operation, you should review the contents and structure of the table to ensure that everything looks correct before you start using the table.

  • Open the destination table in Datasheet view to see whether all data was added to the table.

  • Open the table in Design view to review the data type and other property settings of the fields.

The following table describes the steps that you can take to correct missing or incorrect values.

Tip: While you are troubleshooting the results, if you find just a few missing values, you can add them to the table manually. Conversely, if you find that entire columns or a large number of values are either missing or were not imported properly, you should correct the problem in the source file. After you have corrected all known problems, repeat the import operation.

Issue

Resolution

Graphical elements

Graphical elements, such as logos, charts, and pictures cannot be imported. Manually add them to the database after completing the import operation.

Calculated values

The results of a calculated column or cells are imported, but not the underlying formula. During the import operation, you can specify a data type that is compatible with the formula results, such as Number.

TRUE or FALSE and -1 or 0 values

If the source worksheet or range includes a column that contains only TRUE or FALSE values, Access creates a Yes/No field for the column and inserts -1 or 0 values in the field. However, if the source worksheet or range includes a column that contains only -1 or 0 values, Access, by default, creates a numeric field for the column. You can change the data type of the field to Yes/No during the import operation to avoid this problem.

Multivalued fields

When you import data to a new table or append data to an existing table, Access does not enable support for multiple values in a field, even if the source column contains a list of values separated by semicolon (;). The list of values is treated as a single value and is placed in a text field.

Truncated data

If data appears truncated in a column in the Access table, try increasing the width of the column in Datasheet view. If that doesn’t resolve the issue, the data in a numeric column in Excel is too large for the field size of the destination field in Access. For example, the destination field might have the FieldSize property set to Byte in an Access database but the source data contains a value greater than 255. Correct the values in the source file and try importing again.

Display format

You might have to set the Format property of certain fields in design view to ensure that the values are displayed correctly in Datasheet view. For example:

  • 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.

Null values

You might see an error message at the end of the import operation about data that was deleted or lost during the operation, or when you open the table in Datasheet view, you might see that some field values are blank. If the source columns in Excel are not formatted, or the first eight source rows contain values of different data types, open the source worksheet and do the following:

  • 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:

The values that are missing are of type…

When importing to…

And the destination field type is…

To resolve…

Text

A new table

Date

Replace all text values with date values and then try importing again.

Text

An existing table

Numeric or Date

Replace all text values with values that match the data type of the destination field and then try importing again.

Date values replaced by numeric values

You will see seemingly random five-digit numbers instead of the actual date values in the following situations:

  • The source column in the worksheet contains only numeric values in the first eight rows, but contains some date values in the subsequent rows. These date values will be converted incorrectly.

  • The source column contains date values in some of the first eight rows, and you attempted to import it into a numeric field. These date values will be converted incorrectly.

    To avoid this, replace the date values with numeric values in the source column and try importing again.

    Sometimes, if a column that contains mostly date values also contains several text values, all the date values might appear as seemingly random five-digit numbers. To avoid this, replace the text values with date values and then try importing again.

Numeric values replaced by date values

You will see seemingly random date values instead of the actual numeric values in the following situations:

  • The source column contains only date values in the first eight rows, but contains some numeric values in the subsequent rows. These numeric values will be converted incorrectly.

  • The source column contains numeric values in some of the first eight rows, and you attempted to import it into a date field. These numeric values will be converted incorrectly.

To avoid this, replace the numeric values with date values in the source column and then try importing again.

In addition, you might want to review the error log table (mentioned in the last page of the wizard) in Datasheet view. The table has three fields — Error, Field, and Row. Each row contains information about a specific error, and the contents of the Error field should help you troubleshoot the problem.

Error strings and troubleshooting hints

Error

Description

Field Truncation

A value in the file is too large for the FieldSize property setting for this field.

Type Conversion Failure

A value in the worksheet is the wrong data type for this field. The value might be missing or might appear incorrect in the destination field. See the previous table for more information how to troubleshoot this issue.

Key Violation

This record’s primary key value is a duplicate — it already exists in the table.

Validation Rule Failure

A value breaks the rule set by using the ValidationRule property for this field or for the table.

Null in Required Field

A null value isn’t allowed in this field because the Required property for the field is set to Yes.

Null value in AutoNumber field

The data that you are importing contains a Null value that you attempted to append to an AutoNumber field.

Unparsable Record

A text value contains the text delimiter character (usually double quotation marks). Whenever a value contains the delimiter character, the character must be repeated twice in the text file; for example:

4 1/2″» diameter

Top of Page

Link to data in Excel

By linking an Access database to data in another program, you can use the querying and reporting tools that Access provides without having to maintain a copy of the Excel data in your database.

When you link to an Excel worksheet or a named range, Access creates a new table that is linked to the source cells. Any changes that you make to the source cells in Excel appear in the linked table. However, you cannot edit the contents of the corresponding table in Access. If you want to add, edit, or delete data, you must make the changes in the source file.

Common scenarios for linking to an Excel worksheet from within Access

Typically, you link to an Excel worksheet (instead of importing) for the following reasons:

  • You want to continue to keep your data in Excel worksheets, but be able to use the powerful querying and reporting features of Access.

  • Your department or workgroup uses Access, but data from external sources that you work with is in Excel worksheets. You don’t want to maintain copies of external data, but want to be able to work with it in Access.

If this is the first time you are linking to an Excel worksheet

  • You cannot create a link to an Access database from within Excel.

  • When you link to an Excel file, Access creates a new table, often referred to as a linked table. The table shows the data in the source worksheet or named range, but it doesn’t actually store the data in the database.

  • You cannot link Excel data to an existing table in the database. This means that you cannot append data to an existing table by performing a linking operation.

  • A database can contain multiple linked tables.

  • Any changes that you make to the data in Excel are automatically reflected in the linked table. However, the contents and structure of a linked table in Access are read-only.

  • When you open an Excel workbook in Access (in the File Open dialog box, change the Files of Type list box to Microsoft Excel, and select the file you want), Access creates a blank database and automatically starts the Link Spreadsheet Wizard.

Prepare the Excel data

  1. Locate the Excel file and the worksheet or range that has the data you want to link to. If you don’t want to link to the entire worksheet, consider defining a named range that includes only the cells you want to link to.

    Create a named range in Excel (optional – useful if you only want to link to some of the worksheet data)

    1. Switch to Excel and display the worksheet in which you want to define a named range.

    2. Select the range of cells that contain the data you want to link to.

    3. Right-click within the selected range and click Name a Range or Define Name.

    4. In the New Name dialog box, specify a name for the range in the Name box and then click OK.

      Note that you can link to only one worksheet or range at a time during a link operation. To link to data in multiple places in a workbook, repeat the link operation for each worksheet or range.

  2. Review the source data, and take action as described in the following table:

    Element

    Description

    Tabular format

    Ensure that the cells are in tabular format. If the range includes merged cells, the contents of the cell are placed in the field that corresponds to the leftmost column and the other fields are left blank.

    Skipping columns and rows

    You cannot skip source columns and rows during the linking operation. However, you can hide fields and filter records by opening the linked table in Datasheet view after you have imported them into Access.

    Number of columns

    The number of source columns cannot exceed 255, because Access does not support more than 255 fields in a table.

    Blank columns, rows, and cells

    Delete all unnecessary blank columns and blank rows in the Excel worksheet or range. If there are blank cells, try to add the missing data.

    Error values

    If one or more cells in a worksheet or range contain error values, correct them before you start the import operation. Note that if a source worksheet or range contains error values, Access inserts a null value in the corresponding fields in the table.

    Data type

    You cannot change the data type or size of the fields in the linked table. Before you start the linking operation, you must verify that each column contains data of a specific type.

    We highly recommend that you format a column if it includes values of different data types. For example, the FlightNo column in a worksheet might contain numeric and text values, such as 871, AA90, and 171. To avoid missing or incorrect values, do the following:

    1. Right-click the column and then click Format Cells.

    2. On the Number tab, under Category, select a format.

    3. Click OK.

    First row

    If the first row in the worksheet or named range contains the names of the columns, you can specify that Access should treat the data in the first row as field names during the link operation. If there are no column names in the worksheet, or if a specific column name violates the field naming rules in Access, Access assigns a valid name to each corresponding field.

  3. Close the source file, if it is open.

Prepare the destination database

  1. Open the database in which you want to create the link. Ensure that the database is not read-only and that you have the necessary permissions to make changes to it.

  2. If you don’t want to store the link in any of your existing databases, create a blank database: Click the File tab, click New, and then click Blank Database. Note, if you’re using Access 2007, click the Microsoft Office Button and then click New.

You are now ready to start the linking operation.

Create the link

  1. 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.

  2. In the Get External Data — Excel Spreadsheet dialog box, in the File name box, specify the name of the Excel source file.

  3. Select Link to the data source by creating a linked table, and then click OK.

    The Link Spreadsheet Wizard starts and guides you through the linking process.

  4. On the first page of the wizard, select a worksheet or a named range and click Next.

  5. If the first row of the source worksheet or range contains the field names, select First row contains column headings. Access uses these column headings to name the fields in the table. If a column name includes certain special characters, it cannot be used as a field name in Access. In such cases, an error message is displayed that tells you that Access will assign a valid name for the field. Click OK to continue.

  6. On the final page of the wizard, specify a name for the linked table and then click Finish. If the table with the name you specify already exists, you are asked if you want to overwrite the existing table or query. Click Yes if you want to overwrite the table or query, or click No to specify a different name.

    Access tries to create the linked table. If the operation succeeds, Access displays the Finished linking table message. Open the linked table and review the fields and data to ensure that you see the correct data in all the fields.

    If you see error values or incorrect data, you must troubleshoot the source data. For more information about how to troubleshoot error values or incorrect values, see the next section.

Top of Page

Troubleshoot #Num! and other incorrect values in a linked table

Even if you receive the message Finished linking table, you should open the table in Datasheet view to ensure that the rows and columns show the correct data.

If you see errors or incorrect data anywhere in the table, take correct action as described in the following table, and then try linking again. Remember that you cannot add the values directly to the linked table, because the table is read-only.

Issue

Resolution

Graphical elements

Graphical elements in an Excel worksheet, such as logos, charts, and pictures, cannot be linked to in Access.

Display format

You might have to set the Format property of certain fields in Design view to ensure that the values are displayed correctly in Datasheet view.

Calculated values

The results of a calculated column or cells are displayed in the corresponding field, but you cannot view the formula (or expression) in Access.

Truncated text values

Increase the width of the column in Datasheet view. If you still don’t see the entire value, it could be because the value is longer than 255 characters. Access can only link to the first 255 characters, so you should import the data instead of linking to it.

Numeric field overflow error message

The linked table might appear to be correct, but later, when you run a query against the table, you might see a Numeric Field Overflow error message. This can happen because of a conflict between the data type of a field in the linked table and the type of data that is stored in that field.

TRUE or FALSE and -1 or 0 values

If the source worksheet or range includes a column that contains only TRUE or FALSE values, Access creates a Yes/No field for the column in the linked table. However, if the source worksheet or range includes a column that contains only -1 or 0 values, Access, by default, creates a numeric field for the column, and you will not be able to change the data type of the corresponding field in the table. If you want a Yes/No field in the linked table, ensure that the source column includes TRUE and FALSE values.

Multivalued fields

Access does not enable support for multiple values in a field, even if the source column contains a list of values separated by semicolon (;). The list of values will be treated as a single value, and placed in a text field.

#Num!

Access displays the #Num! error value instead of the actual data in a field in the following situations:

  • If a source column contains a few numeric or date values in a column that contains mostly text values, the numeric and date values are not imported.

  • If a source column contains a few text values in a column that contains mostly numeric values, the text values are not imported.

  • If a source column contains a few text values in a column that contains mostly date values, the text values are not imported.

Do the following to minimize the instances of null values in the table:

  1. Ensure that the source column does not contain values of different data types.

  2. Format the columns in the Excel worksheet.

  3. During the linking operation, select the right data type for each field. If the data type is incorrect, the resulting column might contain only #Num! values for all the rows of data.

Numeric values instead of date values

If you see a seemingly random five-digit number in a field, check to see if the source column contains mostly numeric values but also includes a few date values. Date values that appear in numeric columns get incorrectly converted to a number. Replace the date values with numeric values and then try linking again.

Date values instead of numeric values

If you see a seemingly random date value in a field, check to see if the source column contains mostly date values but also includes a few numeric values. Numeric values that appear in date columns get incorrectly converted to a date. Replace the numeric values with date values and then try linking again.


Top of Page

Примечание: Microsoft Access не поддерживает импорт данных Excel с примененной меткой конфиденциальности. В качестве обходного решения можно удалить метку перед импортом, а затем повторно применить метку после импорта. Дополнительные сведения см. в статье «Применение меток конфиденциальности к файлам и электронной почте в Office».

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

В этой статье приведено подробное описание процедуры импорта или связывания данных Excel с классическими базами данных Access.

В этой статье

  • Общее представление об импорте данных из Excel

  • Импорт данных из Excel

  • Разрешение вопросов, связанных с отсутствующими и неверными значениями

  • Связывание с данными Excel

  • Разрешение вопросов, связанных со значением #Число! и другими неверными значениями в связанной таблице

Общее представление об импорте данных из Excel

Если требуется сохранить данные одного или нескольких листов Excel в Access, следует импортировать содержимое листа в новую или существующую базу данных Access. При импорте данных в Access создается их копия в новой или существующей таблице, а исходный лист Excel не изменяется.

Стандартные сценарии импорта данных Excel в Access

  • Опытному пользователю Excel требуется использовать Access для работы с данными. Для этого необходимо переместить данные из листов Excel в одну или несколько новых таблиц Access.

  • В отделе или рабочей группе используется Access, но иногда данные поступают в формате Excel, и их необходимо объединять с базами данных Access. Требуется выполнить импорт полученных листов Excel в базу данных.

  • Пользователь применяет Access для управления данными, однако получает еженедельные отчеты от остальных участников команды в виде книг Excel. Требуется организовать процесс импорта таким образом, чтобы данные импортировались в базу данных каждую неделю в заданное время.

Первый импорт данных из Excel

  • Сохранить книгу Excel в виде базы данных Access невозможно. В Excel не предусмотрена функция создания базы данных Access с данными Excel.

  • При открытии книги Excel в Access (для этого следует открыть диалоговое окно Открытие файла, выбрать в поле со списком Тип файлов значение Файлы Microsoft Office Excel и выбрать файл) создается ссылка на эту книгу, но данные из нее не импортируются. Связывание с книгой Excel кардинально отличается от импорта листа в базу данных. Дополнительные сведения о связывании см. ниже в разделе Связывание с данными Excel.

Импорт данных из Excel

В этом разделе описано, как подготовиться к операции импорта, выполнить ее и как сохранить параметры импорта в виде спецификации для повторного использования. Помните, что данные можно одновременно импортировать только из одного листа. Импортировать все данные из книги за один раз невозможно.

Подготовка листа

  1. Найдите исходный файл и выделите лист с данными, которые требуется импортировать в Access. Если необходимо импортировать лишь часть данных листа, можно задать именованный диапазон, содержащий только те ячейки, которые требуется импортировать.

    Определение именованного диапазона (необязательно)

    1. Перейдите в Excel и откройте лист, данные из которого нужно импортировать.

    2. Выделите диапазон ячеек, содержащих данные, которые необходимо импортировать.

    3. Щелкните выделенный диапазон правой кнопкой мыши и выберите пункт Имя диапазона или Определить имя.

    4. В диалоговом окне Создание имени укажите имя диапазона в поле Имя и нажмите кнопку ОК.

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

  2. Просмотрите исходные данные и выполните необходимые действия в соответствии с приведенной ниже таблицей.

    Элемент

    Описание

    Число столбцов

    Число исходных столбцов, которые необходимо импортировать, не должно превышать 255, т. к. Access поддерживает не более 255 полей в таблице.

    Пропуск столбцов и строк

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

    Смещ_по_строкам    В ходе операции импорта невозможно фильтровать или пропускать строки.

    Столбцы.    В ходе операции экспорта невозможно пропускать столбцы, если данные добавляются в существующую таблицу.

    Табличный формат

    Убедитесь, что ячейки имеют табличный формат. Если лист или именованный диапазон включает объединенные ячейки, их содержимое помещается в поле, соответствующее крайнему левому столбцу, а другие поля остаются пустыми.

    Пустые столбцы, строки и ячейки

    Удалите все лишние пустые столбцы и строки из листа или диапазона. При наличии пустых ячеек добавьте в них отсутствующие данные. Если планируется добавлять записи к существующей таблице, убедитесь, что соответствующие поля таблицы допускают использование пустых (отсутствующих или неизвестных) значений. Поле допускает использование пустых значений, если свойство Обязательное поле (Required) имеет значение Нет, а свойство Условие на значение (ValidationRule) не запрещает пустые значения.

    Значения ошибок

    Если одна или несколько ячеек на листе или в диапазоне содержат значения ошибок, например #ЧИСЛО или #ДЕЛ, исправьте эти значения до начала операции импорта. Если исходный лист или диапазон содержит значения ошибок, соответствующее поле таблицы Access остается пустым. Дополнительные сведения о способах исправления таких ошибок см. ниже в разделе Разрешение вопросов, связанных с отсутствующими и неверными значениями.

    Тип данных

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

    Рекомендуется также отформатировать все исходные столбцы в Excel и назначить им определенный формат данных перед началом операции импорта. Форматирование является необходимым, если столбец содержит значения с различными типами данных. Например, столбец «Номер рейса» может содержать числовые и текстовые значения, такие как 871, AA90 и 171. Чтобы исключить отсутствующие или неверные значения, выполните указанные ниже действия.

    1. Щелкните заголовок столбца правой кнопкой мыши и выберите пункт Формат ячеек.

    2. На вкладке Числовой в группе Категория выберите формат. Для столбца «Номер рейса» лучше выбрать значение Текстовый.

    3. Нажмите кнопку ОК.

    Если исходные столбцы отформатированы, но все же содержат смешанные значения в строках, следующих за восьмой строкой, в ходе операции импорта значения могут быть пропущены или неправильно преобразованы. Сведения о разрешении этих вопросов см. в разделе Разрешение вопросов, связанных с отсутствующими и неверными значениями.

    Первая строка

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

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

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

Подготовка конечной базы данных

  1. Откройте базу данных Access, в которой будут храниться импортируемые данные. Убедитесь, что база данных доступна не только для чтения и что есть права на ее изменение.

    -или-

    Если ни одна из существующих баз данных не подходит для хранения импортируемых данных, создайте пустую базу данных. Для этого выполните указанные ниже действия.

    Откройте вкладку Файл, нажмите кнопку Создать и выберите пункт Пустая база данных.

  2. Перед началом операции импорта следует определить, в какой таблице будут храниться данные: в новой или существующей.

    Создание новой таблицы.    Если необходимо сохранить данные в новой таблице, в Access создается таблица, в которую добавляются импортируемые данные. Если таблица с указанным именем уже существует, содержимое существующей таблицы перезаписывается импортируемыми данными.

    Добавление в существующую таблицу.    При добавлении данных в существующую таблицу строки из листа Excel добавляются в указанную таблицу.

    Следует помнить, что ошибки в ходе операции добавления зачастую объясняются тем, что исходные данные не соответствуют структуре и параметрам полей в конечной таблице. Чтобы избежать таких ошибок, откройте таблицу в режиме конструктора и проверьте указанные ниже параметры.

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

    • Отсутствующие или лишние поля.    Если одно или несколько полей исходного листа отсутствуют в конечной таблице, их следует добавить до начала операции импорта. Если же таблица содержит поля, которые отсутствуют в исходном файле, их не требуется удалять из таблицы при условии, что они допускают использование пустых значений.

      Совет: Поле допускает использование пустых значений, если его свойство Обязательное поле (Required) имеет значение Нет, а свойство Условие на значение (ValidationRule) не запрещает пустые значения.

    • Первичный ключ.    Если таблица содержит поле первичного ключа, исходный лист или диапазон должен содержать столбец, содержащий значения, совместимые с полем первичного ключа, а импортированные значения ключа должны быть уникальными. Если импортируемая запись содержит значение первичного ключа, которое уже существует в таблице, отображается сообщение об ошибке.

    • Индексированные поля.    Если свойство Индексировано поля таблицы имеет значение Да (без повторов), соответствующий столбец исходного листа или диапазона должен содержать уникальные значения.

      Для выполнения операции импорта перейдите к указанным ниже действиям.

Запуск операции импорта

  1. Расположение мастера импорта или связывания зависит от используемой версии Access. Выполните действия, которые соответствуют вашей версии Access.

    • Если вы используете последнюю версию подписки Microsoft 365 Access или Access 2019, на вкладке «Внешние данные» в группе «Импорт & Link» щелкните «Создать источник данных > из файлового > Excel«.

    • Если вы используете Access 2016, Access 2013 или Access 2010, на вкладке Внешние данные в группе Импорт и связи нажмите кнопку Excel.

    Примечание: Вкладка Внешние данные доступна только в том случае, если открыта база данных.

  2. В диалоговом окне Внешние данные — Электронная таблица Excel в поле Имя файла укажите имя файла Excel, содержащего данные, которые необходимо импортировать.

    -или-

    Чтобы указать импортируемый файл, нажмите кнопку Обзор и воспользуйтесь диалоговым окном Открытие файла.

  3. Укажите способ сохранения импортируемых данных.

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

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

    Сведения о связывании с источником данных путем создания связанной таблицы см. ниже в разделе Связывание с данными Excel.

  4. Нажмите кнопку ОК.

    Будет запущен мастер импорта электронных таблиц, который поможет выполнить импорт. Перейдите к дальнейшим действиям.

Использование мастера импорта электронных таблиц

  1. На первой странице мастера выберите лист, содержащий данные, которые необходимо импортировать, и нажмите кнопку Далее.

  2. На второй странице мастера щелкните элемент листы или именованные диапазоны, выберите лист или именованный диапазон, который необходимо импортировать, и нажмите кнопку Далее.

  3. Если первая строка исходного листа или диапазона содержит имена полей, выберите вариант Первая строка содержит заголовки столбцов и нажмите кнопку Далее.

    Если данные импортируются в новую таблицу, заголовки столбцов используются в Access в качестве имен полей в таблице. Эти имена можно изменить в ходе операции импорта или после ее завершения. Если данные добавляются к существующей таблице, убедитесь, что заголовки столбцов исходного листа в точности соответствуют именам полей конечной таблицы.

    Если данные добавляются к существующей таблице, перейдите к действию 6. Если данные добавляются в новую таблицу, выполните оставшиеся действия.

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

    • Просмотрите и измените имя и тип данных конечного поля.

      В Access выполняется проверка первых восьми строк каждого столбца, чтобы определить тип данных для соответствующего поля. Если первые восемь строк столбца на листе содержат значения разных типов, например текст и числа, мастер предлагает тип данных, совместимый со всеми значениями столбца — как правило, это текстовый тип данных. Хотя можно выбрать и другой тип данных, следует помнить, что значения, несовместимые с этим типом, будут в ходе импорта пропущены или преобразованы неправильно. Дополнительные сведения о том, как исправить неверные или отсутствующие значения, см. ниже в разделе Разрешение вопросов, связанных с отсутствующими и неверными значениями.

    • Чтобы создать индекс для поля, присвойте свойству Индексировано (Indexed) значение Да.

    • Чтобы пропустить весь исходный столбец, установите флажок Не импортировать (пропустить) поле.

      Настроив параметры, нажмите кнопку Далее.

  5. На следующем экране задайте первичный ключ для таблицы. При выборе варианта автоматически создать ключ Access добавляет поле счетчика в качестве первого поля конечной таблицы и автоматически заполняет его уникальными значениями кодов, начиная с 1. После этого нажмите кнопку Далее.

  6. На последнем экране мастера укажите имя целевой таблицы. в поле Импорт в таблицу. Если таблица уже существует, в Access появится запрос на перезапись существующего содержимого таблицы. Нажмите кнопку « Да «, чтобы продолжить, или «Нет», чтобы указать другое имя целевой таблицы, а затем нажмите кнопку « Готово», чтобы импортировать данные.

    Если импорт части или всех данных в Access завершится успешно, в мастере откроется страница с состоянием операции импорта. Кроме того, сведения об операции можно сохранить в виде спецификации для дальнейшего использования. Если операция завершится неудачей, появится сообщение Ошибка при попытке импорта файла.

  7. Нажмите кнопку Да, чтобы сохранить сведения об операции для использования в будущем. Сохранение сведений позволяет выполнять операцию повторно без использования мастера.

Сведения о том, как сохранить спецификацию, см. в статье Сохранение параметров операции импорта или экспорта в виде спецификации.

Сведения о том, как запустить сохраненную спецификацию импорта или экспорта, см. в статье Запуск сохраненной спецификации импорта или экспорта.

Сведения о том, как запланировать выполнение задач импорта и связывания в определенное время, см. в статье Планирование спецификации импорта или экспорта.

Разрешение вопросов, связанных с отсутствующими и неверными значениями

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

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

  • Откройте целевую таблицу в режиме таблицы, чтобы убедиться, что в таблицу были добавлены все данные.

  • Откройте таблицу в режиме конструктора, чтобы проверить типы данных и другие свойства полей.

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

Совет: Если при устранении неполадок обнаружено лишь несколько отсутствующих значений, можно добавить их в таблицу вручную. Если же отсутствует или неправильно импортирован целый столбец либо большой объем данных, следует исправить исходный файл. После устранения всех возможных проблем повторите операцию импорта.

Проблема

Решение

Графические элементы

Графические элементы, такие как логотипы, диаграммы и рисунки, не импортируются. Их следует добавить в базу данных вручную после завершения операции импорта.

Вычисляемые значения

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

Значения TRUE или FALSE и -1 или 0

Если исходный лист или диапазон включает столбец, который содержит только значения TRUE или FALSE, в Access для этого столбца создается логическое поле, в которое вставляется значение -1 или 0. Если же исходный лист или диапазон включает столбец, который содержит только значения -1 и 0, в Access для этого столбца по умолчанию создается числовое поле. Чтобы избежать этой проблемы, можно изменить в ходе импорта тип данных поля на логический.

Многозначные поля

При импорте данных в новую или существующую таблицу приложение Access не поддерживает многозначные поля, даже если исходный столбец содержит список значений, разделенных точками с запятой (;). Список значений обрабатывается как одно значение и помещается в текстовое поле.

Усеченные данные

В случае усечения данных в столбце таблицы Access попытайтесь увеличить ширину столбца в режиме таблицы. Если не удается решить проблему с помощью этого способа, это означает, что объем данных в числовом столбце Excel слишком велик для конечного поля в Access. Например, в базе данных Access свойство FieldSize конечного поля может иметь значение Байт, а исходные данные могут содержать значение больше 255. Исправьте значения в исходном файле и повторите операцию импорта.

Формат отображения

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

  • После завершения импорта в логическом поле в режиме таблицы отображаются значения -1 и 0. Чтобы устранить эту проблему, необходимо после завершения импорта изменить значение свойства Формат этого поля на Да/Нет для отображения флажков.

  • Даты в длинном и среднем форматах отображаются в Access как краткие даты. Чтобы устранить эту проблему, откройте конечную таблицу в Access в режиме конструктора и измените свойство Формат поля даты на Длинный формат даты или Средний формат даты.

Примечание: Если исходный лист содержит элементы форматирования RTF, например полужирный шрифт, подчеркивание или курсив, текст импортируется без форматирования.

Повторяющиеся значения (нарушение уникальности ключа)

Импортируемые записи могут содержать повторяющиеся значения, которые невозможно сохранить в поле первичного ключа в конечной таблице или в поле, для которого свойству Индексировано присвоено значение Да (без повторов). Удалите повторяющиеся значения в исходном файле и повторите операцию импорта.

Значения дат, сдвинутые на 4 года

Значения полей дат, импортированных с листа Excel, оказываются сдвинуты на четыре года. Excel для Windows может использовать две системы дат:

  • Система дат 1904 г. (в которой серийные номера в диапазоне от 0 до 63 918), соответствующие датам с 1 января 1904 г. по 31 декабря 2078 г.

  • Система дат 1900 г. (в которой серийные номера в диапазоне от 1 до 65 380), соответствующие датам с 1 января 1900 г. по 31 декабря 2078 г.

Вы можете задать систему дат в excel Options: File > Options > Advanced> Use 1904 date system.

Примечание    При импорте из книги XLSB всегда используется система дат 1900 независимо от параметра системы дат.

Прежде чем импортировать данные, измените систему дат для книги Excel или выполните после добавления данных запрос на обновление, используя выражение [имя поля даты] + 1462 для корректировки дат.

Excel для macintosh использует только систему дат 1904.

Пустые значения

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

  • Отформатируйте исходные столбцы.

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

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

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

Тип отсутствующих значений

Конечный объект импорта

Тип целевого поля

Решение

Текст

Новая таблица

Поле даты

Замените все текстовые данные значениями дат и повторите попытку импорта.

Текст

Существующая таблица

Числовое поле или поле даты

Замените все текстовые данные значениями, соответствующими типу данных конечного поля, и повторите попытку импорта.

Значения дат, замененные числовыми значениями

Случайные пятизначные числа отображаются вместо фактических значений дат в указанных ниже случаях.

  • Исходный столбец на листе содержит только числовые значения в первых восьми строках, но содержит некоторые значения даты в последующих строках. Эти значения дат будут преобразованы неправильно.

  • Некоторые из первых восьми строк содержат значения дат, которые импортируются в числовые поля. Эти значения дат будут преобразованы неправильно.

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

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

Числовые значения, замененные значениями даты

Случайные значения даты отображаются вместо фактических числовых значений в указанных ниже случаях.

  • Исходный столбец содержит только значения даты в первых восьми строках, но содержит некоторые числовые значения в последующих строках. Эти числовые значения будут преобразованы неправильно.

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

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

Кроме того, может потребоваться просмотреть таблицу ошибок, о которой говорится на последней странице мастера, в режиме таблицы. Эта таблица содержит три поля: «Ошибка», «Поле» и «Строка». В каждой ее строке содержатся сведения об определенной ошибке, и данные в поле «Ошибка» можно использовать при разрешении вопросов.

Строки ошибок и советы по устранению неполадок

Ошибка

Описание

Обрезка полей

Значение в поле превышает размер, заданный свойством FieldSize этого поля.

Ошибка преобразования типа

Значение на листе не соответствует типу данных поля. Это значение может быть заменено пустым или неверным значением в конечном поле. Дополнительные сведения об устранении этой проблемы см. в предыдущей таблице.

Нарушение уникальности ключа

Значение первичного ключа записи совпадает со значением, уже имеющимся в таблице.

Нарушение условия на значение

Значение не соответствует правилу, заданному для этого поля или таблицы с помощью свойства ValidationRule.

Пустое значение в обязательном поле

Данное поле не может иметь пустое значение, поскольку его свойство Обязательное поле (Required) имеет значение Да.

Пустое значение в поле счетчика

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

Неинтерпретируемая запись

Текстовое значение содержит знак разделителя (как правило, это прямые кавычки). Если значение содержит знак разделителя, он должен содержаться в текстовом файле дважды, например:

Диаметр 4 1/2″»

К началу страницы

Связывание с данными Excel

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

При связывании с листом или именованным диапазоном Excel в Access создается новая таблица, связанная с исходными ячейками. Любые изменения, вносимые в исходные ячейки в Excel, отражаются в связанной таблице. При этом изменить содержимое соответствующей таблицы в Access невозможно. Если требуется добавить, изменить или удалить данные, изменения необходимо внести в исходный файл.

Стандартные сценарии связывания с листом Excel из Access

Обычно связывание с листом Excel (вместо импорта) выполняют по указанным ниже причинам.

  • Требуется хранить данные в листах Excel с возможностью использовать удобные функции запросов и отчетов Access.

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

Первое связывание с листом Excel

  • В Excel невозможно создать связь с базой данных Access.

  • При связывании с файлом Excel в Access создается новая таблица, которая называется также связанной таблицей. В ней отображаются данные исходного листа или именованного диапазона; при этом они не сохраняются в базе данных.

  • Данные Excel невозможно связать с существующей таблицей базы данных. Это означает, что операция связывания не позволяет добавлять данные в существующую таблицу.

  • База данных может содержать несколько связанных таблиц.

  • Все изменения данных в Excel автоматически отражаются в связанной таблице. Однако содержимое и структура связанной таблицы Access доступны только для чтения.

  • При открытии книги Excel в Access (для этого в диалоговом окне Открытие файла необходимо выбрать в поле со списком Тип файлов значение Microsoft Excel и выбрать нужный файл) в Access создается пустая база данных и автоматически запускается мастер связи с электронной таблицей.

Подготовка данных Excel

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

    Создание именованного диапазона в Excel (необязательно — целесообразно лишь для связывания отдельных данных на листе)

    1. Перейдите в Excel и откройте лист, в котором нужно определить именованный диапазон.

    2. Выделите диапазон ячеек, содержащих данные, на которые необходимо создать ссылку.

    3. Щелкните выделенный диапазон правой кнопкой мыши и выберите пункт Имя диапазона или Определить имя.

    4. В диалоговом окне Создание имени укажите имя диапазона в поле Имя и нажмите кнопку ОК.

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

  2. Просмотрите исходные данные и выполните необходимые действия в соответствии с приведенной ниже таблицей.

    Элемент

    Описание

    Табличный формат

    Убедитесь, что ячейки имеют табличный формат. Если диапазон включает объединенные ячейки, их содержимое помещается в поле, соответствующее крайнему левому столбцу, а другие поля остаются пустыми.

    Пропуск столбцов и строк

    Во время операции связывания нельзя пропустить исходные столбцы и строки. Однако можно скрыть поля и отфильтровать записи, открыв связанную таблицу в режиме таблицы после их импорта в Access.

    Число столбцов

    Число исходных столбцов не должно превышать 255, т.к. Access поддерживает не более 255 полей в таблице.

    Пустые столбцы, строки и ячейки

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

    Значения ошибок

    Если одна или несколько ячеек на листе или в диапазоне содержат значения ошибок, исправьте эти значения до начала операции импорта. Имейте в виду, что если исходный лист или диапазон содержит значения ошибок, в Access в соответствующее поле таблицы вставляется пустое значение.

    Тип данных

    Изменить тип данных и размер полей в связанной таблице невозможно. Перед началом связывания следует проверить тип данных в каждом столбце.

    Настоятельно рекомендуется отформатировать все столбцы, которые содержат значения с разными типами данных. Например, столбец «Номер рейса» может содержать числовые и текстовые значения, такие как 871, AA90 и 171. Чтобы исключить отсутствующие или неверные значения, выполните указанные ниже действия.

    1. Щелкните столбец правой кнопкой мыши и выберите пункт Формат ячеек.

    2. На вкладке Числовой в группе Категория выберите формат.

    3. Нажмите кнопку ОК.

    Первая строка

    Если первая строка листа или именованного диапазона содержит имена столбцов, можно указать, что приложение Access должно в ходе связывания обрабатывать данные в первой строке как имена полей. Если лист не содержит имен или какое-либо имя столбца не соответствует правилам именования полей в Access, каждому полю назначается допустимое имя.

  3. Закройте исходный файл, если он открыт.

Подготовка конечной базы данных

  1. Откройте базу данных, в которой требуется создать связь. Убедитесь, что база данных доступна не только для чтения и что у вас есть права на внесение в нее изменений.

  2. Если вы не хотите хранить ссылку ни в какой из существующих баз данных, создайте пустую базу данных: перейдите на вкладку «Файл», нажмите кнопку «Создать» и выберите пункт «Пустая база данных». Обратите внимание: если вы используете Access 2007, нажмите кнопку Microsoft Office и выберите пункт Создать.

После этого можно начать операцию связывания.

Создание связи

  1. Расположение мастера импорта или связывания зависит от используемой версии Access. Выполните действия, которые соответствуют вашей версии Access.

    • Если вы используете последнюю версию подписки Microsoft 365 Access или Access 2019, на вкладке «Внешние данные» в группе «Импорт & Link» щелкните «Создать источник данных > из файлового > Excel«.

    • Если вы используете Access 2016, Access 2013 или Access 2010, на вкладке Внешние данные в группе Импорт и связи нажмите кнопку Excel.

    Примечание: Вкладка Внешние данные доступна только в том случае, если открыта база данных.

  2. В диалоговом окне Внешние данные — Электронная таблица Excel в поле Имя файла укажите имя исходного файла Excel.

  3. Выберите вариант Создать связанную таблицу для связи с источником данных и нажмите кнопку ОК.

    Откроется мастер связи с электронной таблицей, который поможет выполнить связывание.

  4. На первой странице мастера выберите лист или именованный диапазон с нужными данными и нажмите кнопку Далее.

  5. Если первая строка исходного листа или диапазона содержит имена полей, выберите вариант Первая строка содержит заголовки столбцов. В Access эти заголовки столбцов используются в качестве имен полей в таблице. Если имя столбца включает специальные знаки, его невозможно использовать как имя поля в Access. В таких случаях отображается сообщение об ошибке, в котором говорится, что полю в Access будет назначено допустимое имя. Нажмите кнопку ОК для продолжения.

  6. На последней странице мастера укажите имя связанной таблицы и нажмите кнопку Готово. Если таблица с указанным именем уже существует, будет предложено перезаписать существующую таблицу или запрос. Нажмите кнопку Да, чтобы перезаписать таблицу или запрос, или кнопку Нет, чтобы указать другое имя.

    Приложение Access попытается создать связанную таблицу. В случае успешного завершения операции появится сообщение Завершено связывание таблицы. Откройте связанную таблицу и просмотрите поля и данные, чтобы убедиться в их правильности.

    При наличии ошибок или неверных данных необходимо устранить ошибки в исходных данных. Дополнительные сведения об устранении ошибок или неверных значений см. в следующем разделе.

К началу страницы

Разрешение вопросов, связанных со значением #Число! и другими неверными значениями в связанной таблице

Даже если появится сообщение Завершено связывание таблицы, откройте таблицу в режиме таблицы и убедитесь, что строки и столбцы содержат правильные данные.

При наличии в таблице ошибок или неверных данных необходимо выполнить действия, описанные в приведенной ниже таблице, и повторить попытку связывания. Следует помнить, что добавить значения непосредственно в связанную таблицу невозможно, т.к. она доступна только для чтения.

Проблема

Решение

Графические элементы

Графические элементы листов Excel, такие как логотипы, диаграммы и рисунки, не могут быть включены в связь с Aсcess.

Формат отображения

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

Вычисляемые значения

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

Усеченные текстовые значения

Увеличьте ширину столбца в режиме таблицы. Если даже после этого значение не отображается целиком, возможно, его длина превышает 255 знаков. В Access связывание возможно только для первых 255 знаков, поэтому вместо связывания следует выполнить импорт данных.

Сообщение о переполнении числового поля

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

Значения TRUE или FALSE и -1 или 0

Если исходный лист или диапазон включает столбец, который содержит только значения TRUE или FALSE, в Access в связанной таблице для этого столбца создается логическое поле. Если же исходный лист или диапазон включает столбец, который содержит только значения -1 или 0, в Access для этого столбца по умолчанию создается числовое поле, тип данных которого невозможно изменить в таблице. Если требуется, чтобы в связанной таблице было создано логическое поле, убедитесь, что исходный столбец содержит значения TRUE и FALSE.

Многозначные поля

В Access многозначные поля не поддерживаются, даже если исходный столбец содержит список значений, разделенных точками с запятой (;). Список значений обрабатывается как одно значение и помещается в текстовое поле.

#Число!

В Access значение ошибки #Число! отображается в полях вместо данных в указанных ниже случаях.

  • Если исходный столбец, который содержит в основном текстовые значения, включает также несколько числовых значений или значений дат, числовые значения и значения дат не импортируются.

  • Если исходный столбец, который содержит в основном числовые значения, включает также несколько текстовых значений, текстовые значения не импортируются.

  • Если исходный столбец, который содержит в основном значения дат, включает также несколько текстовых значений, текстовые значения не импортируются.

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

  1. Убедитесь, что исходный столбец не содержит значения с разными типами данных.

  2. Отформатируйте столбцы на листе Excel.

  3. Во время операции связывания выберите нужный тип данных для каждого поля. Если тип данных неправильный, результирующий столбец может содержать только #Num! Значения для всех строк данных.

Числовые значения, замененные значениями дат

Если поле содержит случайные пятизначные числа, проверьте исходный столбец с числовыми значениями на наличие значений дат. Значения дат в числовых столбцах преобразуются в числа. Замените значения дат числовыми значениями и повторите попытку связывания.

Значения дат, замененные числовыми значениями

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


К началу страницы

Connecting to Microsoft Access Database from Excel VBA, using DAO Object Model

Microsoft Access: Data Access Objects Library (DAO), Connect with Access Databases from Excel using VBA.

Part 1 of 3


Microsoft Access: Data Access Objects Library (DAO), Connect with Access Databases from Excel using VBA

1. Connecting to Microsoft Access Database from Excel VBA, using DAO Object Model.

2. Microsoft Access DAO Object Model: Create an Index, Create Relationship between Fields, Create and Execute a Query.

3. Microsoft Access DAO Object Model: Import or Export Data from Access to Excel.

—————-

Also Read:

Microsoft Access: ActiveX Data Objects (ADO), Connect with Access Databases from Excel using VBA.


————————————————————————————

Contents:

Connect with Databases using DAO, RDO and ADO Objects

DAO Objects & Programming model

The DBEngine object & Workspace Object

DAO Databases

Tables of a DAO Database

Fields / Columns of a Table

Recordset & Records of a DAO Database Table

————————————————————————————

To connect with other databases, when working in VBA, you can use either DAO (Data Access Objects), RDO (Remote Data Objects) or ADO (ActiveX Data Objects). After connecting to a database, you can manipulate its data. DAO, RDO and ADO are data access interfaces ie. they are object and programming models used to access data. Earlier, DAO was used to interface with local databases (viz. MS Access), RDO was used to interface with large databases such as Oracle and SQL Server. ADO was their replacement to interface with all types of data sources. Both DAO and ADO are commonly used while connecting to Microsoft Access Database.

This section explains using the DAO Objects & Programming model to Connect with Access Databases from Microsoft Excel, the DBEngine object, Workspace Object & Workspaces Collection, DAO Databases, Tables of a DAO Database, Fields / Columns of a Table, Recordset & Records of a DAO Database Table, with practical examples.

Connect with Databases using DAO, RDO and ADO Objects

To connect with other databases, when working in VBA, you can use either DAO (Data Access Objects), RDO (Remote Data Objects) or ADO (ActiveX Data Objects). After connecting to a database, you can manipulate its data.

DAO, RDO and ADO are data access interfaces ie. they are object and programming models used to access data. Earlier, DAO was used to interface with local databases (viz. MS Access), RDO was used to interface with large databases such as Oracle and SQL Server. ADO was their replacement to interface with all types of data sources. Both DAO and ADO are commonly used while connecting to Microsoft Access Database. DAO is native to Access, the DAO object library is the default reference in Access 2007 and the library will be existing when you use Access (ADO object library was the default reference in Access 2000 and 2002, whereas DAO returned as the default object library with Access 2003 after being the default in Access 97 earlier). DAO integrates well with Access databases and provides faster access. ADO provides access to a wider variety of data sources than DAO, besides Access. ADO has succeeded DAO and is the latest data access technology, is simpler and more flexible, and interfaces with Microsoft’s powerful data access technology of OLE DB. In ADO the objects are less than in DAO, and it contains more properties, methods and events. ADO/OLE DB is recommended for new projects but it might not be worthwhile to convert DAO code to ADO for existing projects.

ADO creates a reference to the database using the Connection object, to connect to the data source. You use the Open and Close methods to open and close a Connection object. DAO creates a reference to the database using the database object, to connect to the data source.

In Microsoft Access, Recordset objects are used to access and manipulate data in a database. A Recordset object represents a set of records in a database table, or a set of records returned from running a query. Both DAO and ADO libraries have a Recordset object, though the methods, properties, and options of the respective object is different. A Record object is one row of data in a Recordset. A Recordset object has a Fields collection which contains all the Field objects, where each Field object represents a column in the Recordset. In other words, each record represents a row of data and contains many fields, and each field corresponds to a column in the database table.

In your VBA code, you should ideally precede the object name by its program ID (ProgID) prefix, which in ADO is «ADODB» and in DAO is «DAO». Many objects, for example the Recordset object, have similar names in both DAO and ADO and it is advisable to have explicit references in your project. This becomes a must if you have included references to both the DAO and ADO libraries in your VBA project, else the object library mentioned first in the References list will prevail, resulting in confusion in the vba code.

While instantiating the Recordset object, you should use:

Dim daoRecSet As DAO.Recordset

Dim adoRecSet As ADODB.Recordset

instead of:

Dim RecSet As Recordset

DAO Objects & Programming model

DAO (Data Access Objects) is an object-oriented data access interface, used to connect to and access databases. It was the first Objects & Programming model which used the Microsoft Jet database engine, and is optimized to work Microsoft Access files (.mdb). The objects and collections in the DAO object hierarchy are used to connect to a database, access and manipulate its data and database structure.

A database engine is the underlying software component of a database used to manipulate its data. DAO Object Model by default uses the Microsoft Jet database engine for data access. ODBCDirect (which came after ODBC) allowed DAO to access ODBC data sources directly without using the Jet database engine. In this section we will illustrate connecting to Microsoft Access Database using DAO with the Jet engine. Prior to Access 2007, Access used the Microsoft (JET) engine, but with Access 2007 the new and improved ACE engine has succeeded and replaced JET. The ACE engine is fully backward-compatible so that it can be used with the .accdb files (Access 2007) and the earlier .mdb files.

Automating Access from Excel: You can connect to and access a database using DAO, from external applications which support automation (viz. MS Excel, MS Word, etc.), and in this section we show how to do this from Microsoft Excel by using VBA. With automation you can control another application (MS Access) within your host application (MS Excel) without any manual intervention. Automation is used typically to run macros or queries from Excel to connect to or create or manipulate MS Access database and its structure, to access and manipulate MS Access data and reports, to import data from MS Access to Excel for creating charts and pivot tables and otherwise use the data for calculations and analysis.

ODBC (Open Database Connectivity):

ODBC (Open Database Connectivity) is an interface which enables an application to connect and access a relational database, using the SQL query syntax. An ODBC database is a DBMS (Database Management System) for which there is an appropriate ODBC driver (examples of DBMS include SQL Server, Oracle, AS/400, Foxpro, Microsoft Access). The ODBC Driver is a software that resides between the ODBC Client (which is the front-end application wherein the driver is loaded) and the DBMS (wherein the data is stored for access), and it translates the command into a format that is understood by the DBMS. DAO Object Model uses the Microsoft Jet database engine and is optimized to work Microsoft Access files (.mdb), but ODBC databases can also be accessed with DAO and the Microsoft Jet database engine. A database engine is the underlying software component of a database used to manipulate its data. Jet (Joint Engine Technology) is used by Microsoft Access as its database engine.

OLE DB and ODBC:

OLE DB was intended as a successor to improve on ODBC by providing an enhanced and faster interface for data access. OLE DB is not bound to the SQL language like ODBC and it supports all forms of data sources (ie. relational and non-relational data sources including mainframe and hierarchical databases, e-mail and file systems, text and graphical data, custom business objects, …) whereas ODBC was limited to relational databases. OLE DB was complex to be used directly with Visual Basic and Microsoft’s ADO (ActiveX Data Objects) Object Model was introduced which interfaces with an OLE DB provider and enables an application (viz. Excel) to access and manipulate data from a database (viz. MS Access).

ODBC vs DAO, ADO vs DAO:

When working with ODBC data sources, use ODBC. With ODBC you can access any data source for which there is an appropriate ODBC driver for the database you want to access. Examples of ODBC databases include Oracle, Microsoft SQL Server, Microsoft Visual FoxPro, IBM DB2, Microsoft Access. When working with Microsoft Jet (.mdb) databases, using DAO will be more efficient. Examples of Microsoft Jet databases include Micorsoft Access, Microsoft SQL Server, Paradox. DAO Object Model uses the Microsoft Jet database engine and is optimized to work Microsoft Access files (.mdb), but ODBC databases can also be accessed with DAO and the Microsoft Jet database engine when you want the Jet database engine’s speed and DAO’s extra functionality. DAO precedes ADO and ODBC precedes OLE DB. ADO/OLE DB is recommended for new projects but it might not be worthwhile to convert DAO code to ADO for existing projects.

Add a reference to the DAO Object Library

To use DAO in your VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE, and then choose an appropriate version (mostly, you should choose the highest version number), which is «Microsoft DAO 3.6 Object Library» for Access 2000 onwards.

The DBEngine object

The highest level object in the DAO object model is the DBEngine object, and it contains all objects in the hierarchy of DAO objects. There can only be one DBEngine object and there is no collection of which it is an element of. The DBEngine object has many properties and methods, and contains 2 collections — the Workspaces collection and the Errors collection. You can configure the database engine with properties and methods provided by the DBEngine object. A database engine is the underlying software component of a database used to manipulate its data. You can refer to DBEngine directly without explicitly declaring an object variable of type DBEngine.

Workspace Object & Workspaces Collection

Create a Workspace object to define a user session by name, in which a user performs all database operations by using the Microsoft Access database engine. The Workspace object allows you to open multiple databases or connections in a session, and you can open additional sessions with the Workspace object. A Workspace session starts on creation of a new Workspace object and ends when the Workspace object Close method is used. Multiple sessions (ie. workspace objects) are specifically useful when you want to perform operations as different users or when you want to manage separate and independent operations in each session. All active and unhidden workspace objects are called the Workspaces collection, which is contained in the DBEngine object. In DAO, when you open databases, they automatically exist within the default workspace which is the first workspace in the Workspaces collection. A default workspace, DBEngine.Workspaces(0), is automatically created when a Workspace object is first referred to or used, with the name as «#Default Workspace#», and if security is not enabled with username as «admin» (if security is implemented then username is set to the name of the user who logs on).

You can use the CreateWorkspace method to create a Workspace object. It is not necessary to append a Workspace object to the Wokspaces collection after creating it, and in this case you will need to refer it by the object variable used in the CreateWorkspace method. It will be required to append a Workspace object to the Wokspaces collection after creating it, if you want to refer to it from the Workspaces collection by its ordinal number or Name viz. DBEngine.Workspaces(0) or DBEngine.Workspaces(«WorkspaceObjectName») or DBEngine.Workspaces![WorkspaceObjectName]. All defined DAO Workspace objects appended to the collection comprise the Workspaces collection. There are 2 types of Workspace objects, as defined by WorkspaceTypeEnum Enumeration in the CreateWorkspace method — (i) Microsoft Jet Workspace objects (type — ‘dbUseJet’) which creates a Microsoft Access workspace; and (ii) ODBCDirect workspaces (type — ‘dbUseODBC’) which are  not supported in Microsoft Office Access 2007. In this section we will discuss only the Microsoft Jet Workspace objects.

By default the DBEngine.DefaultUser Property is set to «Admin» and the DBEngine.DefaultPassword Property is set to a zero-length string («») and the default Workspace object’s user and password are defined accordingly. When you start Access or access an Access database with vba, all users automatically log-in with the default name «Admin» and the password of zero-length string («»), but to access a database in a secured system (ie. a secured Access Database) users must provide a username and a password (if a password has been assigned to the user). In a secured system, for the default workspace you set the DefaultUser and DefaultPassword properties (for the DBEngine object), and after the default session has been initialized, additional sessions can be created with user names and passwords. Note that password is case-sensitive but not the username. In this section we do not go into further details of accessing a secured Microsoft Access database.

DBEngine.CreateWorkspace Method

Use the DBEngine.CreateWorkspace Method to create a new Workspace object. Syntax: DBEngineObject.CreateWorkspace(Name, UserName, Password, UseType). All arguments, except UseType, are mandatory. In the Name argument, specify a unique Workspace name for a session. In the UserName argument, specify the name of the user for identification. In the Password argument, you are required to enter a password for the Workspace object with a maximum of 20 characters. The UseType argument specifies one of the WorkspaceTypeEnum values: (i) dbUseJet — (Microsoft Jet Workspace objects) which creates a Microsoft Access workspace, and is also the default; and (ii) dbUseODBC — for ODBCDirect workspaces which are  not supported in Microsoft Office Access 2007.

In DAO, when you open databases, they automatically exist within the default workspace which is the first workspace in the Workspaces collection. You need to use the DBEngine.CreateWorkspace Method only to create a second workspace which is seldom required.

Example 1: DAO WorkSpace Object & Workspaces Collection.

1. Create a new Workspace object, using the CreateWorkspace method, and append to the Workspaces collection.
2. Access properties of all workspace objects (ie. default workspace and the newly created workspace).

Sub AccessDAO_CreateWorkspace_1()
‘Create a new Workspace object, using the CreateWorkspace method, and append to the Workspaces collection.

‘Access properties of all workspace objects (ie. default workspace and the newly created workspace).

‘To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE.

Dim strMyPath As String, strDBName As String, strDB As String
Dim wrkSpace As DAO.Workspace, wrkSpaceNew As DAO.Workspace
Dim prpWrkSpace As DAO.Property

‘create a new Microsoft Jet Workspace, with the default type of dbUseJet:
Set wrkSpaceNew = DBEngine.CreateWorkspace(«newWS», «admin», «», dbUseJet)

‘append the new workspace to the Workspaces collection:
DBEngine.Workspaces.Append wrkSpaceNew

‘return the number of workspace objects in the Workspaces collection (returns 2 — default & new workspace):
MsgBox DBEngine.Workspaces.count

‘access properties of all workspace objects (ie. default workspace and the newly created workspace):
For Each wrkSpace In DBEngine.Workspaces

‘workspace name (returns «#Default Workspace#» & «newWS»):

MsgBox «Workspace Name: » & wrkSpace.Name

‘username property setting:

MsgBox wrkSpace.UserName

‘properties of workspace object:

For Each prpWrkSpace In wrkSpace.Properties

MsgBox «Property Name: » & prpWrkSpace.Name

Next prpWrkSpace

Next wrkSpace

‘returns the name of the default Workspace, ie. «#Default Workspace#»:
MsgBox DBEngine.Workspaces(0).Name
‘because the Workspace object has been appended to the Wokspaces collection after creating it, we can refer to it from the Workspaces collection by its ordinal number or Name (returns «newWS»):
MsgBox DBEngine.Workspaces(«newWS»).Name
‘if the Workspace object had not been appended to the Wokspaces collection after creating it, in this case you would have had to refer it by the object variable used in the CreateWorkspace method (returns «newWS»):
MsgBox wrkSpaceNew.Name

‘close the objects:
wrkSpaceNew.Close

‘destroy the variables:
Set wrkSpace = Nothing
Set wrkSpaceNew = Nothing
Set prpWrkSpace = Nothing

End Sub

DAO Workspace Object Methods

DAO Workspace Object Methods: The Close Method is used to close an open Workspace. CreateDatabase method is used to create a new database and the OpenDatabase method is used to open an existing database. To manage transaction processing during a session (ie. when a series of database changes made in a session are treated as one unit), you have three transaction methods of BeginTrans, CommitTrans and Rollback. The OpenConnection Method, available only in an ODBCDirect workspace, is used to open a connection to an ODBC data source. Note that Microsoft Office Access 2007 does not support ODBCDirect workspaces.

DAO Databases

DBEngine.OpenDatabase Method

Use the DBEngine.OpenDatabase Method to open a Database, as specified by its name/path. A reference to the Database object variable (to which the database is assigned) is returned by this method, and the database is not actually opened in the Microsoft Access window. If you open a database object without specifying a workspace, it will exist within the default workspace: DBEngine.Workspaces(0). Syntax: DBEngineObject.OpenDatabase(Name, Options, ReadOnly, Connect). Name argument is mandatory while all other arguments are optional. In the Name argument you will specify the database file name and full path, which you want to open. In the Options argument, you can specify False which is the Default and opens the database in shared mode while specifying True opens the database in exclusive mode. In the ReadOnly argument specifying False (default) will open the database with read-write access and specifying True will open in read-only. Connect argument is used to specify connection information (ex. password).

DAO Workspace.OpenDatabase Method

Use the DAO Workspace.OpenDatabase Method to open a Database, as specified by its name/path, in the specified Workspace object. A reference to the Database object variable (to which the database is assigned) is returned by this method, and the database is not actually opened in the Microsoft Access window. Syntax: WorkspaceObject.OpenDatabase(Name, Options, ReadOnly, Connect). The arguments are similar to as in the DBEngine.OpenDatabase Method, explained above.

DAO DBEngine.CreateDatabase Method

Use the DAO DBEngine.CreateDatabase Method to create, open and save a new Database. A reference to the Database object variable (to which the new database is assigned) is returned by this method. Note that this method creates a new empty database, which you will need to structure and enter content thereafter. If you create a database object without specifying a workspace, it will exist within the default workspace: DBEngine.Workspaces(0). Syntax:  DBEngineObject.CreateDatabase(Name, Locale, Option). Name and Locale arguments are mandatory. In the Name argument (max 255 characters) you will specify the file name and full path of the database which is being created. The Locale argument specifies a collating order for the database (this is equated with the Database.CollatingOrder Property which specifies the database sort order sequence) ie. the character set to be used to determine how database values will be sorted. Specifying the constant «dbLangGeneral» for this argument means creating a database which will support sorting for «English, German, French, Portuguese, Italian, and Modern Spanish». A password for the new Database can also be created in concatenation with the constant specified in the Locale argument viz. dbLangGeneral & «;pwd=123», where password is «123». The Option argument specifies a constant to determine the version for the data format and if the database should be encrypted, and not specifying a constant will create an un-encrypted database.

DAO Workspace.CreateDatabase Method

Use the DAO Workspace.CreateDatabase Method to create, open and save a new Database. A reference to the Database object variable (to which the new database is assigned) is returned by this method. Note that this method creates a new empty database, which you will need to structure and enter content thereafter. This method creates a new Database and opens it in the specified workspace object. Syntax:  Workspace.CreateDatabase(Name, Locale, Option). The arguments are similar to as in the DBEngine.CreateDatabase Method, explained above.

Example 2: Open an existing Database, Create a new Database.

1. Open an existing Database using the DAO OpenDatabase Method.
2. Create a new Database using the DAO CreateDatabase Method.
3. Return Databases and enumerate their properties in a Workspace.

Sub AccessDAO_OpenDatabaseCreateNewDatabase_2()
‘Create a New Microsoft Jet Workspace; Open an existing Database using the DAO OpenDatabase Method; Create a new Database using the DAO CreateDatabase Method; Return Databases and enumerate their Properties in a Workspace;

‘To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE.

Dim strMyPath As String, strDBName As String, strDB As String, strDBNameNew As String, strDBNew As String
Dim daoDB As DAO.Database, daoDBNew As DAO.Database, daoDBS As DAO.Database
Dim wrkSpaceNew As DAO.Workspace
Dim prpDB As DAO.Property

‘—————
‘SET DATABASE NAMES (EXISTING & NEW):

‘your data source with which to establish connection — ENTER the existing MS Access Database Name:
strDBName = «SalesReport.accdb»
‘get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
‘set the string variable to the Database:
strDB = strMyPath & «» & strDBName

‘name of the new MS Access Database being created:
strDBNameNew = «SalesReportNew.accdb»
‘set the string variable to the new Database:
strDBNew = strMyPath & «» & strDBNameNew

‘—————
‘CREATE A NEW MICROSOFT JET WORKSPACE:

‘create a new Microsoft Jet Workspace, with the default type of dbUseJet:
Set wrkSpaceNew = DBEngine.CreateWorkspace(«newWS», «admin», «», dbUseJet)

‘append the new workspace to the Workspaces collection:
DBEngine.Workspaces.Append wrkSpaceNew

‘—————
‘OPEN AN EXISTING DATABASE:

‘open the database in the default workspace:
‘Set daoDB = DBEngine.Workspaces(0).OpenDatabase(strDB)
‘If you open a database object without specifying a workspace, it will exist within the default workspace:
‘Set daoDB = DBEngine.OpenDatabase(strDB)

‘If you open a database by specifying a workspace object, it will exist within the specified workspace:
Set daoDB = wrkSpaceNew.OpenDatabase(strDB, True)
‘alternatively:
‘Set daoDB = DBEngine.Workspaces(«newWS»).

OpenDatabase(strDB, False)

‘—————
‘CREATE A NEW DATABASE:

‘If you create a database object without specifying a workspace, it will exist within the default workspace:
Set daoDBNew = DBEngine.CreateDatabase(strDBNew, dbLangGeneral)
‘alternatively, to create a new database and open in the new Workspace object:
‘Set daoDBNew = wrkSpaceNew.CreateDatabase(strDBNew, dbLangGeneral)

‘—————
‘ACCESS DATABASES IN EACH WORKSPACE (DEFAULT AND NEW WORKSPACE):

‘return the number of database objects in the new Workspace:
MsgBox «No of database objects in the new Workspace: » & wrkSpaceNew.Databases.count

‘access databases in the new workspace:
For Each daoDBS In wrkSpaceNew.Databases

MsgBox daoDBS.Name

For Each prpDB In daoDBS.Properties

MsgBox «Property Name: » & prpDB.Name

Next prpDB

Next daoDBS

‘return the number of database objects in the default Workspace:
MsgBox «No of database objects in the default Workspace: » & DBEngine.Workspaces(0).Databases.count

‘access databases in the default workspace:
For Each daoDBS In DBEngine.Workspaces(0).Databases

MsgBox daoDBS.Name

For Each prpDB In daoDBS.Properties

MsgBox «Property Name: » & prpDB.Name

Next prpDB

Next daoDBS

‘—————
‘close the objects:
daoDB.Close
daoDBNew.Close
wrkSpaceNew.Close

‘destroy the variables:
Set daoDB = Nothing
Set daoDBNew = Nothing
Set daoDBS = Nothing
Set wrkSpaceNew = Nothing
Set prpDB = Nothing

End Sub

Return a Reference to the Current Database — CurrentDb Method

Use the CurrentDb Method to return a reference to the database which is currently open in the Microsoft Access window, from vba code. The method returns a database object, without the need to specfy the database name. You can use other DAO objects with the database object variable returned by this method. A reference to the current database is provided by the first member of the Databases collection. The reference pointed to the current database by using the syntax DBEngine(0)(0) can also be used but this syntax refers to the open copy of the current database, whereas with the CurrentDb method you can create ‘multiple database object variables’ referring to the current database because this method creates a new instance of the current database making it amenable for multi users. However, it is much slower to use CurrentDb than using DBEngine(0)(0). Note that another Database can be opened and worked upon simultaneously, using the OpenDatabase method, while the current database is already open in the Microsoft Access window.

Example 3: CurrentDb Method — return a reference to the currently open database.

Sub AccessDAO_ReferCurrentDatabase_3()
‘CurrentDb Method — return a reference to the currently open database.

‘To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE.

Dim strMyPath As String, strDBName As String, strDB As String
Dim daoCDB1 As DAO.Database, daoCDB2 As DAO.Database, daoDB As DAO.Database
Dim recSet As DAO.Recordset

‘—————
‘RETURN MULTIPLE INSTANCES OF THE DATABASE CURRENTLY OPEN IN THE MICROSOFT ACCESS WINDOW:

‘assign current database reference to multiple object variables of type Database:
Set daoCDB1 = CurrentDb
Set daoCDB2 = CurrentDb

MsgBox daoCDB1.Name
MsgBox daoCDB2.Name

‘refer DAO TableDef Object in current database — you need to first assign the current database reference to an object variable (ex. daoCDB2):
Dim daoTblDef As DAO.TableDef
Dim fld As DAO.Field
Set daoTblDef = daoCDB2.TableDefs(«SalesManager»)

For Each fld In daoTblDef.Fields

MsgBox fld.Name

Next fld

‘—-
‘USE CurrentDb DIRECTLY WITH A RECORDSET OBJECT:

‘CurrentDb can be used directly with a Recordset object, while in most other DAO objects you need to first assign the current database reference to an object variable as above.
Set recSet = CurrentDb.OpenRecordset(«SalesManager», dbOpenDynaset)

‘displays first 3 fields of the first record:
MsgBox recSet.Fields(0)
MsgBox recSet.Fields(1)
MsgBox recSet.Fields(2)

‘—————
‘OPEN ANOTHER DATABASE USING THE OpenDatabase METHOD, TO WORK ON SIMULTANEOUSLY, WHILE THE CURRENT DATABASE IS ALREADY OPEN IN THE MICROSOFT ACCESS WINDOW:

‘your data source with which to establish connection — ENTER the MS Access Database Name:
strDBName = «SalesReport.accdb»
‘get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
‘set the string variable to the Database:
strDB = strMyPath & «» & strDBName

‘open the database in the default workspace:
Set daoDB = DBEngine.OpenDatabase(strDB)

MsgBox daoDB.Name

‘—————
‘close the objects:
recSet.Close
daoCDB1.Close
daoCDB2.Close
daoDB.Close

‘destroy the variables:
Set daoCDB1 = Nothing
Set daoCDB2 = Nothing
Set daoDB = Nothing
Set daoTblDef = Nothing
Set fld = Nothing

Set recSet = Nothing

End Sub

Tables of a DAO Database

TableDef Object and TableDefs collection

A TableDef object, with its properties and methods, is used to manipulate a table definition. With a TableDef object you can: create a new table (Database.CreateTableDef Method); create or add a new Field in a table (TableDef.CreateField Method); create a new Index (TableDef.CreateIndex Method); create a new Recordset and append it to the Recordsets collection (TableDef.OpenRecordset Method); update a linked table’s connection information (TableDef.RefreshLink Method); set or return information about a linked table (TableDef.Connect Property); set or return the name of a linked table (ableDef.SourceTableName Property); set or return validation value/rule for a field’s data (TableDef.ValidationRule Property); set or return the text message displayed when the field value does not conform to the ValidationRule (TableDef.ValidationText Property); and so on.

All stored TableDef objects in a database are referred to as the TableDefs collection. You create a new TableDef object using the Database.CreateTableDef Method. It is required to append a TableDef object to the TableDefs collection after creating it, using the DAO TableDefs.Append Method. You can refer to a TableDef object in the TableDefs collection by its ordinal number or Name viz. TableDefs(0) or TableDefs(«TableDefObjectName») or TableDefs![TableDefObjectName].

Database.CreateTableDef Method

Use the Database.CreateTableDef Method to create a new TableDef object. Syntax: DatabaseObject.CreateTableDef(Name, Attributes, SourceTableName, Connect). All arguments are optional to specify. The Name argument sets the name of the TableDef object, which can be a maximum of 64 characters. The Attributes argument sets a value indicating characteristic(s) of the TableDef object. The Attributes Property is read/write for a TableDef object till it is appended to its collection. The SourceTableName argument specifies the name of a linked or the base table that is the original data source in an external database. The Connect argument is a String value, which provides information of a TableDef object’s linked table or an open database source, consisting of a database type specifier and a database path.

Note that it is required to define one Field atleast before you can append a TableDef object to the TableDefs collection. Use the TableDefs.Delete Method to delete a TableDef object from the TableDefs collection.

Fields / Columns of a Table

A Field object corresponds to a column of data of similar data type and properties. The Index, QueryDef, Relation and TableDef objects all have a Fields collection, which represents all stored Field objects as specified in the respective object. The Recordset object also has a Fields collection, which represents all stored Field objects in a record or a row of data. A field object has its own properties & methods by which it is manipulated.

Create a new Field

TableDef.CreateField Method 

Use the TableDef.CreateField Method to create a new Field object. Syntax: TableDefObject.CreateField(Name, Type, Size). All arguments are optional to specify. The Name argument specifies a name for the new Field. The Type argument sets the data type of the Field, as indicated by a constant. The Size argument determines the maximum size of a Field. For a Field with character data (except Memo), size determines the maximum number of characters; for numeric fields, it is the maximum size in bytes (of storage). Text fields can be set upto a maximum of 255 characters for a Microsoft Access database, whereas for non-Text fields the size is automatically determined by their Type property. Not specifying the Size will default the Field size to as permissible by the database. For Memo or Long Binary Fields use the Field.FieldSize Property to determine the size in the number of bytes used in the database, whereas use the Size property for all other Field data types.

You can use the CreateField method to add a new field to an Index or Relation object. To add a field to an Index object, use the DAO Index.CreateField Method, Syntax: IndexObject.CreateField(Name, Type, Size). The type and size arguments are not supported for an Index object, and are ignored in this case. To add a field to a Relation object, use the DAO Relation.CreateField Method, Syntax: RelationObject.CreateField(Name, Type, Size). The type and size arguments are not supported for a Relation object, and are ignored in this case.

Fields Collection Properties & Methods

Count the number of Fields

The Count property of the fields collection determines the number of fields in a collection, wherein numbering for members of a collection begins with zero. If you have seven fields in a Recordset, using RecordsetObject.Fields.count will return 7, and RecordsetObject.Fields(0) will return the value of the first field [OrdinalPosition of the first field is 0].

Access Fields by their ordinal position or Name property

You can Access Fields by their ordinal position or Name property viz. Recordset.Fields.(Name/OrdinalPosition). Recordset.Fields(0).Name returns the Name of the first field, and Recordset.Fields(0).Value returns the content in the first field. The Value property of the Field object is its Default property viz Recordset.Fields(0) is the same as Recordset.Fields(0).Value and will return the first fields’s value.

Examples: To reference a field named «FirstName», which is the second field in the table, you can use any of the following:-

RecordsetObject.Fields(«FirstName»)

RecordsetObject.Fields(1)

RecordsetObject![FirstName]

DAO Fields.Append Method

To add or append a new field to the Fields Collection of a TableDef or an Index object, use the DAO Fields.Append Method. To add a field to a table, use the Syntax: TableDefObject.Append(FieldObject). To add a field to an Index, use the Syntax: IndexObject.Append(FieldObject). The FieldObject argument mentions the Field Object variable which is being appended and is necessary to specify.

DAO Fields.Delete Method

To delete a field from the Fields Collection, use the DAO Fields.Delete Method. To delete a field from a table, use the Syntax: TableDefObject.Fields.Delete(Name). The Name argument mentions the name of the Field which is being deleted and is necessary to specify. Note that once an index referencing a field has been created, that Field cannot be deleted from a Fields collection of a TableDef object.

DAO Fields.Refresh Method

The relative position of a Field object within the Fields collection is usually the order in which the field has been appended in the collection, the first appended field at first position will have an OrdinalPosition of 0 (zero), the second appended field at second position will have an OrdinalPosition of 1, and so on, and this position can be changed (or returned) by using the DAO Field.OrdinalPosition Property. A change in the ordinal position of a Field may not change the order of the Fields in the collection unless the DAO Fields. Refresh Method is used. The Refresh method is particularly required to be used in a multi-user environment wherein different users might be making changes in the database, in which case only those objects are contained when you have referred to the collection initially without reflecting any subsequent changes made by other users, and the collection will get updated only on using the Refresh method.

Field Object Properties

Field properties are used to determine or return the name, size, type and characteristics of a Field. Some of these properties are elaborated below.

DAO Field.Name Property

Use the DAO Field.Name Property to set or return a Field’s name. It is a String value not exceeding 64 characters. The property is read-only after the Field object is appended to the Fields collection, before which it is read/write.

DAO Field.Value Property

Use the Field.Value Property to return, enter or edit the data in a Field. This is the default property of a Field object viz. you can refer to a field object without specifying the value property. For example, entering «Lisa» in the field named «FirstName» can be done either as RecordSetObject.Fields(«FirstName») = «Lisa» or as RecordSetObject.Fields(«FirstName»).Value = «Lisa».

DAO Field.OrdinalPosition Property

The relative position of a Field object within the Fields collection is usually the order in which the field has been appended in the collection, the first appended field at first position will have an OrdinalPosition of 0 (zero), the second appended field at second position will have an OrdinalPosition of 1, and so on, and this position can be changed (or returned) by using the DAO Field.OrdinalPosition Property. Note that this property uses «relative postion» so that if you have 3 fields and you change the OrdinalPosition property of these to 10, 12 & 15, then the field with OrdinalPosition value of 12 will be returned in an order relative to the others, ie. between the fields whose values have been set as 10 and 15.

The property is read-write for a Field object before it is appended to a Fields collection. After a Field object is appended, for Fields contained within a TableDef object it is read-write, and for fields contained within Recordset or QueryDef objects it is read-only, but the property is not supported for fields contained within Index & Relation objects.

DAO Field.Size Property

The Field.Size Property determines the maximum size of a Field. For a Field with character data (except Memo), size determines the maximum number of characters; for numeric fields, it is the maximum size in bytes (of storage). For Text fields you must set the Size property which can be set upto a maximum of 255 characters for a Microsoft Access database, whereas for non-Text fields the size is automatically determined by their Type property. Not specifying the Size will default the Field size to as permissible by the database. For Memo or Long Binary Fields use the Field.FieldSize Property to determine the size in the number of bytes used in the database, whereas use the Size property for all other Field data types.

The property is read-write for a Field object before it is appended to a Fields collection. After a Field object is appended, the property is supported for Fields contained within a TableDef object, Recordset object or QueryDef object, wherein it is read-only, but the property is not supported for fields contained within Index & Relation objects. 

DAO Field.Type Property

Use the Type property to set or return the operational or data type of a Field. The value returned by this property is a constant which indicates the data type of a field. The property is read-only after the Field object is appended to the Fields collection or to any object, before which it is read/write.

Examples of data type constants that are supported by DAO, for the Type property, include:

dbBoolean (Boolean Value — Yes/No); dbChar (Char); dbCurrency (Currency); dbDate (Date); dbDouble (Double); dbGUID (GUID); dbInteger (Integer); dbBigInt (Big Integer); dbSingle (Single); dbLong (Long); dbMemo (Memo); dbText (Text); ….

DAO Field.Attributes Property

Use the DAO Field.Attributes Property to set (or return) the Field characteristics. The Field characteristic(s) is specified by a value or constant, which can be: dbAutoIncrField (to automatically increment the Field value to a unique Long integer); dbDescending (to sort Field values in a descending order — default sort order for a Field is Ascending if this attribute is not specified — this attribute is applicable only to an index field ie. to Fields collection of an Index); dbFixedField (dbFixedField specifies that the field has a fixed size —  numeric fields have a Fixed field size by default — maps to ADO column attribute adColFixed); dbVariableField (valid only  for text fields, it specifies a Variable Field size ie. the Text data type Field can store variable text lengths); dbUpdatableField (when the Field value can be updated or changed); dbHyperlinkField (hyperlink field, valid only for Memo field types); dbSystemField (these fields cannot be deleted).

To create an auto-increment field, set data type of field to Long and set Attributes property to dbAutoIncrField. An auto-increment field (also referred to as AutoNumber field) by default starts at 1 and increments sequentially and can be used aptly as a primary key field to automatically insert unique numbers in a field.

Set multiple attributes — sum the respective constants (using the plus «+» sign) to set multiple attributes, wherein any non-meaningful values get ignored without giving an error.

This property is read/write for a field before being appended to a collection. For a Field object after it is appended to a collection: for Fields contained within a TableDef object, the property is read/write; for Fields contained within an Index object, this property remains read-write until the TableDef object which contains the Index object is appended to a Database and then read-only thereafter; for Fields contained within a Recordset object or QueryDef object, the property is read-only; for Fields contained within a Relation object this property is not supported.

DAO Field.DefaultValue Property

Use the Field.DefaultValue Property to specify the default value to be entered in a Field automatically on creation of a new record. A text or an expression of String data type upto a maximum of 255 characters, can be specified as the default value. For AutoNumber and Long Binary fields, this property is not applicable.

The property is read-write for a Field object before it is appended to a Fields collection. After a Field object is appended, for Fields contained within a TableDef object it is read-write, and for fields contained within Recordset or QueryDef objects it is read-only, but the property is not supported for fields contained within Index & Relation objects.

DAO Field.Required Property

The Field.Required Property determines whether a field can accept null values. Setting the Property to False will allow null values in the field. Between an Index object and a Field object, set the Required property for the Field object because its validation for the Field object precedes that of an Index object.

The property is read-write for a Field object before it is appended to a Fields collection. After a Field object is appended, for Fields contained within a TableDef object it is read-write, and for fields contained within Recordset or QueryDef objects it is read-only, but the property is not supported for fields contained within Index & Relation objects.

DAO Field.AllowZeroLength Property

Setting the Field.AllowZeroLength Property to True will allow value for Text or Memo data type Fields to be set to an empty or zero-length string («»). Zero Length string vs Null value: Note that in Access when you specify a Zero Length string it means that you actually specify a value, and when you set the Required porperty to be True it means that the Field can have a Null value which means that NO value needs to be entered — for the user there is no visible difference between the two.

The property is read-write for a Field object before it is appended to a Fields collection. After a Field object is appended, for Fields contained within a TableDef object it is read-write, and for fields contained within Recordset or QueryDef objects it is read-only, but the property is not supported for fields contained within Index & Relation objects.

DAO Field.ValidationRule Property

Use the Field.ValidationRule Property to validate a field’s data with a specified rule or condition. The property specifies a string value as a comparison like in a WHERE clause (as used in SQL statements) but does not use the WHERE word. If the field’s value does not conform to the specified rule or condition, the error message (a string value) as specified by the ValidationText property gets displayed. Only databases using the Microsoft Access database engine support validation.

The property is read-write for a Field object before it is appended to a Fields collection. After a Field object is appended, for Fields contained within a TableDef object it is read-write, and for fields contained within Recordset or QueryDef objects it is read-only, but the property is not supported for fields contained within Index & Relation objects.

DAO Field.ValidationText Property

Validation Text specifies the error message (a string value) which gets displayed if the field’s value does not conform to the specified rule or condition specified by the ValidationRule property.

The property is read-write for a Field object before it is appended to a Fields collection. After a Field object is appended, for Fields contained within a TableDef object it is read-write, and for fields contained within Recordset or QueryDef objects it is read-only, but the property is not supported for fields contained within Index & Relation objects.

Example 4a: Create Tables and Fields in a DAO Database.

Refer Image 4a as mentioned in the code.

1. Create a New Database;
2. Create & Append Tables (ie. TableDef objects);
3. Create & Append Fields;
4. Enumerate Tables in the Database and their Properties;
5. Enumerate Fields in a Table;
6. Delete Fields & Tables;

Sub AccessDAO_CreateTablesCreateFields_4a()
‘Create a New Database;
‘Create & Append Tables (ie. TableDef objects);
‘Create & Append Fields;
‘Enumerate Tables in the Database and their Properties;
‘Enumerate Fields in a Table;
‘Delete Fields & Tables;

‘To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE.

Dim strMyPath As String, strDBName As String, strDB As String
Dim daoDB As DAO.Database
Dim daoTD As DAO.TableDef, daoTD1 As DAO.TableDef, daoTD2 As DAO.TableDef
Dim daoFld As DAO.Field
Dim daoPrp As DAO.Property

‘—————
‘get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
‘name of the new MS Access Database being created:
strDBName = «SalesReportNew.accdb»

‘set the string variable to the new Database:

strDB = strMyPath & «» & strDBName

‘—————
‘CREATE A NEW MS ACCESS DATATABASE, TABLES AND FIELDS:
‘Refer Image 4a to view Tables & Fields (in «SalesManager» Table) of the new Database («SalesReportNew.accdb») after running below code, before deleteing any table or field.

‘Create a New Database: If you create a database object without specifying a workspace, it will exist within the default workspace:
Set daoDB = DBEngine.CreateDatabase(strDB, dbLangGeneral)

‘Create Tables (ie. TableDef objects) named «SalesManager» and «Performance»:
Set daoTD1 = daoDB.CreateTableDef(«SalesManager»)

Set daoTD2 = daoDB.CreateTableDef(«Performance»)

‘Before you append the TableDef object to the TableDefs collection, you will create Fields and append them to the new TableDef object (Table named «SalesManager») created above:

With daoTD1

‘create a new auto increment field, and set attribute:
‘set data type of field to Long, set Attributes property to dbAutoIncrField. An auto-increment field (also referred to as AutoNumber field) by default starts at 1 and increments sequentially and can be used aptly as a primary key field to automatically insert unique numbers in a field.
.Fields.Append .CreateField(«EmployeeId», dbLong)
.Fields(«EmployeeId»).Attributes = dbAutoIncrField + dbFixedField

‘create a Text field, maximum 30 characters, and required.
Set daoFld = .CreateField(«FirstName», dbText, 30)
daoFld.Attributes = dbVariableField
daoFld.Required = True
.Fields.Append daoFld

‘Text field, allow zero length, and max 25 characters:
.Fields.Append .CreateField(«SurName», dbText, 25)
.Fields(«SurName»).Required = True
.Fields(«SurName»).AllowZeroLength = True

‘create a Date field with a validation rule and Validation Text:
Set daoFld = .CreateField(«JoinDate», dbDate)
‘specify a default value for the field:
daoFld.DefaultValue = «#04/01/2010#»
‘validate the field’s value, before it is set, with a specified rule or condition:
daoFld.ValidationRule = «>=#04/01/2010# and <=date()»
‘specify the error message which gets displayed if the field’s value does not conform to the specified rule or condition:
daoFld.ValidationText = «JoinDate should be on or after 04/01/2010 but within current date»
.Fields.Append daoFld

‘Currency Field and required:
.Fields.Append .CreateField(«Sales», dbCurrency)
.Fields(«Sales»).Required = True

‘create a Boolean (Yes/No) field:
.Fields.Append .CreateField(«NewJoinee?», dbBoolean)

‘create a Hyperlink field, and set the attribute:
Set daoFld = .CreateField(«WebProfile», dbMemo)
daoFld.Attributes = dbHyperlinkField + dbVariableField

.Fields.Append daoFld

End With

‘Before you append the TableDef object to the TableDefs collection, you will create Fields and append them to the new TableDef object (Table named «Performance») created above:

With daoTD2

.Fields.Append .CreateField(«FirstName», dbText)

End With

‘Save/Append the tables «SalesManager» & «Performance» to the TableDefs collection:
daoDB.TableDefs.Append daoTD1
daoDB.TableDefs.Append daoTD2

‘—————
‘ENUMERATE DATABASE TABLES AND PROPERTIES:

‘return number of Tables in database:
MsgBox daoDB.TableDefs.count

‘Enumerate Tables in the database and their properties:
For Each daoTD In daoDB.TableDefs

‘Use the Attributes property to ignore System and Hidden Tables. The Attributes argument returns or sets a value indicating characteristic(s) of the TableDef object. Note, that to check a specific attribute we have used the logical AND operator for comparison of: (i) the TableDef Attributes property and the dbSystemObject constant; and (ii) the TableDef Attributes property and the dbHiddenObject constant. You can alternatively do an equivalency test using numerical values of the constants.
If ((daoTD.Attributes And dbSystemObject) Or (daoTD.Attributes And dbHiddenObject)) Then
Else

For Each daoPrp In daoTD.Properties

MsgBox «Table Name: » & daoTD.Name & » —   Property Name: » & daoPrp.Name & «,   Property Type: » & daoPrp.Type & «,   Property Value: » & daoPrp.Value

Next

End If

‘Alternate If statement to ignore System and Hidden Tables: dbSystemObject constant has a numerical value of -2147483646; dbHiddenObject constant has a numerical value of 1;

‘If daoTD.Attributes >= 0 And daoTD.Attributes <> 1 Then

‘MsgBox «Table Name: » & daoTD.Name

‘End If

Next

‘—————
‘ENUMERATE TABLE FIELDS:

‘return number of Fields in the Table named «SalesManager»:
MsgBox daoTD1.Fields.count

‘Enumerate Fields and return their name, type & size in the Table named «SalesManager»:

For Each daoFld In daoTD1.Fields

MsgBox daoFld.Name & «, » & daoFld.Type & «, » & daoFld.Size

Next

‘—————
‘DELETE FIELDS AND TABLES IN DATABASE:

‘Delete a field in the Table named «SalesManager»:
‘daoTD1.Fields.Delete «SurName»

‘Delete the Table (TableDef object) named «Performance» created above:
‘daoDB.TableDefs.Delete daoTD2.Name
‘or
daoDB.TableDefs.Delete «Performance»

‘—————
‘close the objects:
daoDB.Close

‘destroy the variables:
Set daoDB = Nothing
Set daoTD = Nothing
Set daoTD1 = Nothing
Set daoTD2 = Nothing
Set daoFld = Nothing

Set daoPrp = Nothing

End Sub

Recordset & Records of a DAO Database Table

After connecting to a database, you can manipulate its data. In Microsoft Access, Recordset objects are used to access and manipulate data in a database. A Recordset object represents a set of records in a database table, or a set of records returned from running a query. Both DAO and ADO libraries have a Recordset object, though the methods, properties, and options of the respective object is different. A Record object is one row of data in a Recordset. A Recordset object has a Fields collection which contains all the Field objects, where each Field object represents a column in the Recordset. In other words, each record represents a row of data and contains many fields, and each field corresponds to a column in the database table.

In your VBA code, you should ideally precede the object name by its program ID (ProgID) prefix, which in ADO is «ADODB» and in DAO is «DAO». Many objects, for example the Recordset object, have similar names in both DAO and ADO and it is advisable to have explicit references in your project. This becomes a must if you have included references to both the DAO and ADO libraries in your VBA project, else the object library mentioned first in the References list will prevail, resulting in confusion in the vba code.

While instantiating the Recordset object, you should use:

Dim daoRecSet As DAO.Recordset

Dim adoRecSet As ADODB.Recordset

instead of:

Dim RecSet As Recordset

DAO Recordset Types

There are five types of Recordsets:

1. A Table-type recordset is based on a Table and not on a query. A Table-type recordset is created only when working with a single non-linked table. Valid for Microsoft Access Jet workspaces only. You can use the Seek method (but not the Find Method) to search through this recordset (using a Table index), which is faster than using the Find method.

2. A Dynaset-Type recordset results from a query. The set of records can contain fields from one or more underlying tables or any linked table (ie. any table linked to the Access Database). The recordset gets dynamically updated and reflects any change made to the underlying records. After the recordset has been created it does not add any new record satisfying the criteria. This recordset type supports the Find method (but not the Seek method) to search through the recordset, which is however slower than the Seek method.

3. A Snapshot-type recordset shows the data as at the time when a snapshot is taken ie. when a recordset is created. The set of records can contain fields from one or more underlying tables or any linked table. This recordset type is a static copy of the records and does not get dynamically updated and does not reflect any change made to the underlying records. If a field value is changed in a record, it will not be updated dynamically like it gets done in a Dynaset-Type recordset and you will need to refresh the recordset to update. This recordset type is used to read data and searching through this recordset is very fast. This recordset type supports the Find method to search through the recordset.

4. A Forward-only-type recordset is identical to a snapshot-type wherein only scroll forward through records is possible.

5. A Dynamic-type recordset results from a query from one or more underlying tables. In this recordset you can add, change or delete records from a row-returning query. This recordset is similar to the Dynaset-Type except that after running a query the matching records added, deleted or edited in the underlying tables by other users also get automatically reflected in the recordset of this type. Valid for ODBCDirect workspaces only.

All active recordsets of a database are contained in the Recordsets collection, wherein a recordset gets appended to the collection when it is opened and gets removed from the collection when it is closed (using the Close method). Each recordset object contains a collection of the fields and a collection of the indexes in the underlying table.

DAO Recordset.Type Property

Use the Recordset.Type Property to set or return the type of Recordset, using the RecordsetTypeEnum constants or values. There are five settings: dbOpenTable (value-1, Table-type, for Microsoft Access workspaces only); dbOpenDynaset (value-2, Dynaset-type); dbOpenSnapshot (value-4, Snapshot-type); dbOpenForwardOnly (value-8, Forward-only type); dbOpenDynamic (value-16, Dynamic-type, for ODBCDirect workspaces only).

Create a new Recordset object

Create a Recordset object and append it to the Recordsets collection, using the OpenRecordset method. You can use the OpenRecordset method to open a Recordset that is based on a Table, SQL statement, stored or parameter query as detailed below. Arguments have the same meaning across the OpenRecordset methods.

DAO Database.OpenRecordset Method. Syntax: DatabaseObject.OpenRecordset(Name, Type, Options, LockEdit). In this method you pass the Table name to the method and use the Set operator to return the recordset.

Only the Name argument is mandatory to specify while other arguments are optional. The Name argument specifies the source of records and can be the name of a table or a query, or it can be an SQL statement. In the Type argument, specify one of the five types for the recordset by using the constants: dbOpenTable (Table-type); dbOpenDynaset (Dynaset-type); dbOpenSnapshot (Snapshot-type); dbOpenForwardOnly (Forward-only type); dbOpenDynamic (Dynamic-type). A Recordset created in a Microsoft Access local table without specifying the Type will default to Table-type. Executing the OpenRecordset method on a linked table or query, without specifying the Type, will default to Dynaset-type. In the Options argument you can specify one of the many constants representing the recordset’s characteristics viz. specifying dbReadOnly opens a recordset as read-only, and so on. The LockEdit argument specifies a constant which determines the type of record locking used when a recordset is opened.

DAO TableDef.OpenRecordset Method. Syntax: TableDefObject.OpenRecordset(Type, Options). In this method you first get a reference to the Table (TableDefObject) and then use the Set operator to return the recordset.

DAO Recordset.OpenRecordset Method. Syntax: RecordsetObject.OpenRecordset(Type, Options). In this method you first get a reference to a Recordset Object and then use the Set operator. Refer Example 7 wherein this method is used to Filter Records.

Creating a Recordset, based on a stored query or a parameter query, using the QueryDef.OpenRecordset Method. For details on this method, refer section «Create and Exceute a Query».

Create a new record in a Database Table — use the AddNew & Update methods

DAO Recordset.AddNew method

Create a new record for a Recordset object, using the Recordset.AddNew method. Syntax: RecordsetObject.AddNew. When you use this method, the field’s value is set to its default value and in the absence of a default value specification, it is set to Null. Ensure that after adding a new record using the AddNew method or after making any changes in a record using the Edit method, you must save the record and/or any changes to it by using the Update method BEFORE you perform any operation like move to another record or use the Edit or AddNew method again or close the recordset or set bookmark property for another record.

In DAO, after using the Update method, the current record will be the record which had focus before the AddNew method. Using the LastModified property (for a DAO recordset) returns a Bookmark pointing to the most recent added / modified record and setting the Bookmark property to this bookmark will make the new record as the current record.

When you add a record to a dynaset-type Recordset, using the AddNew method, the new record will appear at the end of the recordset disregrading the recordset’s sorting if any. In this case you can re-create the recordset or use the ReQuery method to have the new record appear in its sorted position. When a record is added to a table-type Recordset, the new record appears in accordance with the recordset’s index and in the absence of an index the new record will appear at the end of the recordset.

DAO Recordset.Update Method

Ensure that after adding a new record using the AddNew method or after making any changes in a record using the Edit method, you must save the record and/or any changes to it by using the Recordset.Update Method BEFORE you perform any operation like move to another record or use the Edit or AddNew method again or close the recordset or set bookmark property for another record. Syntax: RecordsetObject .Update(UpdateType, Force). Both arguments of UpdateType & Force are optional.

Recordset.LastModified Property

In Table-type or Dynaset-Type recordsets, a bookmark of the record which has most recently been added or changed, is returned by the Recordset.LastModified Property. Use this property to bookmark and move to the record which has last been added or modified. Syntax: RecordsetObject.LastModified. Refer Example 4b for using this property.

Recordset.Bookmark Property

Use the Recordset.Bookmark Property to uniquely identify the current record by setting or returning a bookmark. You can create any number of bookmarks in a recordset, by saving each bookmark and assigning its value to a variable and then return to that record by setting the Recordset’s Bookmark property to the variable. Refer Example 4b for using this property.

Edit Records in a Recordset

Use the DAO Recordset.Edit Method to make changes to fields of the current record in a Recordset object. Ensure that after making any changes in a record using the Edit method, you must save the changes to it by using the Update method. After editing the record, the current record to which changes are made remains current ie. the record with focus. Syntax: RecordsetObject.Edit.

Moving between Records in a Recordset

DAO Recordset.Move Method. Syntax: RecordsetObject.Move(Rows, StartBookmark). This method moves the position of the current record as per the specified number of rows (Rows argument) starting from a bookmarked record specified by the StartBookmark argument or from the current record if this argument is omitted. It is necessary to specify the Rows argument, and if this is more than 0 the current record moves forward towards end of recordset, and if less than 0 then the current record moves backwards. You can use this method with rows argument set to 0, to retrieve the current record’s underlying data.

MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (DAO): MoveFirst method moves the current record to the first record. Remember that on opening a recordset, the first record is the current record. Using the MoveLast method moves the current record to the last record in the recordset. MoveNext method moves the current record one position forward and MovePrevious moves the current record one position backward. Note that the MoveFirst, MoveLast, and MovePrevious methods cannot be used on a Forward-only-type recordset. Syntax: RecordsetObject.MoveFirst, RecordsetObject.MoveLast, RecordsetObject.MoveNext, RecordsetObject.MovePrevious.

EOF Property (DAO) indicates whether the current record position is after the last record in the set of records, wherein its value will be TRUE. BOF Property (DAO) indicates whether the current record position is before the first record in the set of records, wherein its value will be TRUE. Both properties return a Boolean value and are used to determine if the current record is outside the limits of the Recordset object. There will be no current record if either the EOF Property or BOF Property is True, and if both properties are True on opening a recordset it will indicate that there are no records. Opening a Recordset having atleast one record makes the first record as the current record and in this case both the EOF Property and BOF Property will be False. Syntax: RecordsetObject .EOF, RecordsetObject .BOF.

Count the number of Records in a Recordset

Use the DAO Recordset.RecordCount Property to: (i) count the number of records which have been acceessed in a Dynaset-Type or Snapshot-type or Forward-only-type recordset, and after the last record is accessed (ie. after the recordset is populated) RecordCount indicates the total number of records contained in the recordset; or (ii) count the total number of records in a table-type Recordset or in a TableDef object, wherein RecordCount always returns the correct number. To forcibly access the last record in a Dynaset-Type or Snapshot-type or Forward-only-type recordset, use the Recordset.MoveLast method. Syntax: RecordsetObject.RecordCount.

Close DAO objects, using the Close Method

You should close an open Recordset by using the DAO Recordset.Close Method, which will free any associated system resources. Similarly, close an open Workspace object using the Workspace.Close Method and close an open Database using the Database.Close Method. Closing an object is not enough to remove it from memory, for which you need to set the object variable to Nothing, after closing the object.

To close a Recordset: RecordsetObject.Close

To destroy the Recordset variable: Set RecordsetObject = Nothing

Example 4b: Add / Edit Records and Enter Data, in Tables.

Refer Image 4b as mentioned in the code.

1. Add new records to a table using the AddNew method;
2. Edit records using the Edit method;
3. Use the Recordset.Bookmark Property to identify the current record;
4. Use Recordset.LastModified Property pointing to the most recent added / modified record.

Sub AccessDAO_AddRecordsEnterData_4b()
‘Add new records to a table using the AddNew method;
‘edit records using the Edit method;
‘Use the Recordset.Bookmark Property to identify the current record;
‘Use Recordset.LastModified Property pointing to the most recent added / modified record.

‘To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE.
‘Refer Image 4b after running below code which adds & edits records in the database file created in example 4a above (note that the field «SurName» of «SalesManager» Table has not been deleted).

Dim strMyPath As String, strDBName As String, strDB As String, recBookMark As String
Dim daoDB As DAO.Database
Dim recSet As DAO.Recordset

‘—————
‘your data source with which to establish connection — ENTER the MS Access Database Name:
strDBName = «SalesReportNew.accdb»
‘get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
‘set the string variable to the Database:
strDB = strMyPath & «» & strDBName

‘If you open a database object without specifying a workspace, it will exist within the default workspace. First assign the database reference to an object variable:
Set daoDB = DBEngine.OpenDatabase(strDB)

‘Open a table-type recordset based on a MS Access Table named «SalesManager»:
Set recSet = daoDB.OpenRecordset(«SalesManager»)

‘—————-
‘add new records to a table, using the AddNew method (of the Recordset object):
With recSet

.AddNew
‘you need not enter a value for the auto-incrementing field of «EmployeeId»; the start value is 1. In DAO you cannot set the Seed of the auto-number, however you can start at a specific value in a new table by entering the specific value for the first record of an AutoNumber field and subsequent records will increment from this specific start value.
.Fields(«EmployeeId») = 55
.Fields(«FirstName») = «Lisa»
.Fields(«SurName») = «Randall»
‘enter a date/time value between # and #, or within double-quotes:
.Fields(«JoinDate») = «08/11/2012»
.Fields(«Sales») = «22456»
.Fields(«NewJoinee?») = True
‘for a hyperlink field, use both # and double-quotes:
.Fields(«WebProfile») = «#http://www.google.com#»
‘will save only after Update method is run:

.AddNew
‘note that «JoinDate» field is omitted, hence its default value will be entered
.Fields(«FirstName») = «Tracy» & » » & «Von»
.Fields(«SurName») = «Murray»
.Fields(«Sales») = «41098»
.Fields(«NewJoinee?») = False
.Fields(«WebProfile») = «#http://www.yahoo.com#»
.Update
‘second record — save position of current record:
.Bookmark = .LastModified

.AddNew
.Fields(«FirstName») = «John»
.Fields(«SurName») = «Mason»
.Fields(«JoinDate») = #9/2/2012#
.Fields(«Sales») = «31478»
.Fields(«NewJoinee?») = True
.Fields(«WebProfile») = «#http://www.msn.com#»

‘In DAO, after the Update, the current record will be the record which had focus before the AddNew. Using the LastModified property (for a DAO recordset — it does not work with an ADO recordset) returns a Bookmark pointing to the most recent added / modified record. This makes the new record as the current record.

.Bookmark = .LastModified

End With

‘returns «John»
MsgBox recSet.Fields(«FirstName»)

‘edit the new record, using the Edit method (of the Recordset object):
With recSet

‘Recordset.Edit Method is valid for a DAO recordset, it does not work with an ADO recordset:
.Edit
.Fields(«FirstName») = «Julia»
.Fields(«SurName») = «Willis»
‘will save only after Update method is run:

.Update

End With

‘returns «Julia»
MsgBox recSet.Fields(«FirstName»)

 ‘return the second record whose position was saved:
recSet.Bookmark = recBookMark
‘returns «Tracy Von»
MsgBox recSet.Fields(«FirstName»)

 ‘—————
‘close the objects:
daoDB.Close

‘destroy the variables:
Set daoDB = Nothing

End Sub

Example 5a: Open Recordset, Enumerate Recordset, Recordset Properties, Navigate through Records.

1. OpenRecordset method of the Database object — Open Recordset based on a Table; Open Recordset based on a SQL statement.
2. OpenRecordset method of the TableDef object — Open Recordset based on a Table.
3. Enumerate the Recordset; List all valid properties of Recordset.
4. Use the MoveFirst and MoveNext methods to navigate through records, together with EOF Property.

Sub AccessDAO_OpenRecordsetMoveThruRecords_5a()
‘OPEN RECORDSET; ENUMERATE RECORDSET; RECORDSET PROPERTIES; NAVIGATE THROUGH RECORDS:
‘OpenRecordset method of the Database object — Open Recordset based on a Table; Open Recordset based on a SQL statement.
‘OpenRecordset method of the TableDef object — Open Recordset based on a Table.
‘Enumerate the Recordset; List all valid properties of Recordset.
‘Use the MoveFirst and MoveNext methods to navigate through records, together with EOF Property.

‘To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE.

Dim strMyPath As String, strDBName As String, strDB As String, strSQL As String
Dim daoDB As DAO.Database
Dim recSet As DAO.Recordset
Dim daoTblDef As DAO.TableDef
Dim daoFld As DAO.Field
Dim daoPrp As DAO.Property
Dim n As Long, i As Long

‘—————
‘your data source with which to establish connection — ENTER the MS Access Database Name:
strDBName = «SalesReport.accdb»
‘get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
‘set the string variable to the Database:
strDB = strMyPath & «» & strDBName

‘If you open a database object without specifying a workspace, it will exist within the default workspace. First assign the database reference to an object variable:
Set daoDB = DBEngine.OpenDatabase(strDB)

‘—————
‘OpenRecordset METHOD OF THE DATABASE OBJECT — OPEN RECORDSET BASED ON A TABLE:

‘Open table-type, read-only recordset based on a MS Access Table:
Set recSet = daoDB.OpenRecordset(«SalesManager», dbOpenTable, dbReadOnly)

‘return the first field (name & value) of each record of the Recordset:

‘while moving forward within a recordset, use EOF so as not to cross the last record. EOF Property indicates that the current record position is after the last record in the set of records.

Do While Not recSet.EOF

MsgBox recSet.Fields(0).Name & » — » & recSet.Fields(0).Value

‘MoveNext method moves the current record one position forward.

recSet.MoveNext

recSet.Close

Set recSet = Nothing

‘——
‘OpenRecordset METHOD OF THE DATABASE OBJECT — OPEN RECORDSET BASED ON AN SQL STATEMENT:

‘Open dynaset-type recordset based on a SQL statement:
strSQL = «SELECT * FROM SalesManager WHERE EmployeeId > 18″
Set recSet = daoDB.OpenRecordset(strSQL, dbOpenDynaset)

‘Enumerate the Recordset — all fields in each record of the Recordset:
fieldsCount = recSet.Fields.count
n = 1

‘navigate through records in a recordset:
With recSet

‘MoveFirst method moves the current record to the first record.
.MoveFirst
Do While Not .EOF

MsgBox «Record No. » & n
For i = 0 To fieldsCount — 1

MsgBox .Fields(i).Name & » — » & .Fields(i).Value

Next i

.MoveNext

n = n + 1

Loop

recSet.Close

Set recSet = Nothing

‘——
‘OpenRecordset METHOD OF THE TableDef OBJECT — OPEN RECORDSET BASED ON A TABLE:

‘refer to a TableDef object by its name: reference the table named SalesManager
Set daoTblDef = daoDB.TableDefs(«SalesManager»)

‘Open snapshot-type recordset based on a MS Access Table:
Set recSet = daoTblDef.OpenRecordset(dbOpenSnapshot, dbReadOnly)

‘List all fields of each record of the Recordset:
Do While Not recSet.EOF

For Each daoFld In recSet.Fields

MsgBox daoFld.Name & » — » & daoFld.Value

Next daoFld

recSet.MoveNext

‘List all valid properties of the Recordset object:
For Each daoPrp In recSet.Properties

‘skip invalid values with resume next statement

On Error Resume Next

MsgBox «Property Name: » & daoPrp.Name & «;     Property Value: » & daoPrp.Value

Next daoPrp

‘—————
‘close the objects:
recSet.Close
daoDB.Close

‘destroy the variables:
Set daoDB = Nothing
Set recSet = Nothing
Set daoTblDef = Nothing
Set daoFld = Nothing

End Sub

Example 5b: Count the number of Records in a Recordset — DAO Recordset.RecordCount Property.

Refer Image 5 as mentioned in the code.

Sub AccessDAO_RecordCount_5b()
‘Count the number of Records in a Recordset — DAO Recordset.RecordCount Property
‘refer Image 5 to view the SalesManager Table in MS Access file «SalesReport.accdb», on which RecordCount is done in this code.

‘To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE.

Dim strMyPath As String, strDBName As String, strDB As String, strSQL As String
Dim daoDB As DAO.Database
Dim recSet As DAO.Recordset
Dim daoTblDef As DAO.TableDef
Dim qryD As DAO.QueryDef

‘—————
‘your data source with which to establish connection — ENTER the MS Access Database Name:
strDBName = «SalesReport.accdb»
‘get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
‘set the string variable to the Database:
strDB = strMyPath & «» & strDBName

‘assign the database reference to an object variable:
Set daoDB = DBEngine.Workspaces(0).OpenDatabase(strDB)

‘—————
‘RecordCount in a TableDef object:
Set daoTblDef = daoDB.TableDefs(«SalesManager»)
‘returns 5, refer Image 5:
MsgBox «RecordsCount in a TableDef Object: » & daoTblDef.RecordCount

‘——
‘RecordCount in a Table-type recordset:
Set recSet = daoDB.OpenRecordset(«SalesManager», dbOpenTable)
‘returns 5, refer Image 5:
MsgBox «RecordsCount in Table-type recordset: » & recSet.RecordCount

recSet.Close
Set recSet = Nothing

‘——
‘RecordCount in a Dynaset-Type recordset:
strSQL = «SELECT * FROM SalesManager WHERE EmployeeId > 18″
Set qryD = daoDB.CreateQueryDef(«sqlQuery», strSQL)

Set recSet = qryD.OpenRecordset(dbOpenDynaset)
‘returns 1, refer Image 5:
MsgBox «RecordsCount in Dynaset-Type recordset BEFORE MoveLast: » & recSet.RecordCount
recSet.MoveLast
‘returns 3, refer Image 5:
MsgBox «RecordsCount in Dynaset-Type recordset AFTER MoveLast: » & recSet.RecordCount

daoDB.QueryDefs.Delete («sqlQuery»)

recSet.Close
Set recSet = Nothing

‘——
‘RecordCount in a Snapshot-type recordset:
Set recSet = daoDB.OpenRecordset(«SalesManager», dbOpenSnapshot)
‘returns 1, refer Image 5:
MsgBox «RecordsCount in Snapshot-type recordset BEFORE MoveLast: » & recSet.RecordCount
recSet.MoveLast
‘returns 5, refer Image 5:
MsgBox «RecordsCount in Snapshot-type recordset AFTER MoveLast: » & recSet.RecordCount

recSet.Close
Set recSet = Nothing

‘——
‘RecordCount in a Forward-only-type recordset:
Set recSet = daoDB.OpenRecordset(«SalesManager», dbOpenForwardOnly)
‘returns 1, refer Image 5:
MsgBox «RecordsCount in Forward-only-type recordset BEFORE MoveNext: » & recSet.RecordCount
recSet.MoveNext
‘returns 2, refer Image 5:
MsgBox «RecordsCount in Forward-only-type recordset AFTER first MoveNext: » & recSet.RecordCount
recSet.MoveNext
‘returns 3, refer Image 5:
MsgBox «RecordsCount in Forward-only-type recordset AFTER second MoveNext: » & recSet.RecordCount

‘——
‘close the objects:
recSet.Close
daoDB.Close

‘destroy the variables:
Set daoDB = Nothing
Set recSet = Nothing
Set daoTblDef = Nothing

End Sub

Example 6: Find Method (FindFirst & FindNext) in a Dynaset or Snapshot-type recordset; Edit / Delete Records.

Refer Images 6a, 6b & 6c as mentioned in the code.

1. Locate records matching specified criteria using the FindFirst and FindNext methods in a dynaset or snapshot-type recordset;
2. Edit a record using the Edit method;
3. Delete a record using the Delete method.

Sub AccessDAO_FindMethod_EditDeleteRecords_6()
‘Locate records matching specified criteria using the FindFirst and FindNext methods in a dynaset or snapshot-type recordset;
‘Edit a record using the Edit method;
‘Delete a record using the Delete method;

‘To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE.
‘refer Image 6a to view the existing SalesManager Table in MS Access file «SalesReport.accdb».

Dim strMyPath As String, strDBName As String, strDB As String
Dim daoDB As DAO.Database
Dim recSet As DAO.Recordset

‘—————
‘your data source with which to establish connection — ENTER the MS Access Database Name:
strDBName = «SalesReport.accdb»
‘get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
‘set the string variable to the Database:
strDB = strMyPath & «» & strDBName

‘assign the database reference to an object variable:
Set daoDB = DBEngine.Workspaces(0).OpenDatabase(strDB)

‘Open a dynaset-type recordset based on a MS Access Table named «SalesManager»:
Set recSet = daoDB.OpenRecordset(«SalesManager», dbOpenDynaset)

‘—————-
‘USE FindFirst AND FindNext METHODS TO LOCATE ALL RECORDS THAT MATCH A SPECIFIED CRITERIA:

‘locate first record with matching criteria:
recSet.FindFirst «SurName LIKE ‘*A*'»

‘if a record with matching criteria is found:
If recSet.NoMatch = False Then

‘the NoMatch property is set to True, if no matched record is found:

Do While Not recSet.NoMatch

‘return record with matching criteria: returns Murray, Mason & Davis: refer Image 6a:

MsgBox recSet.Fields(«SurName»)

‘locate next record with matching criteria:

recSet.FindNext «SurName LIKE ‘*A*'»

Loop

Else

MsgBox «No Matching Record Found!»

‘———————
‘LOCATE RECORD TO EDIT, USING THE FindFirst METHOD:
‘refer Image 6b after running below code:

‘recSet.FindFirst «FirstName = ‘Jim'»
‘recSet.FindFirst «SurName = «»Murray»»»
recSet.FindFirst «EmployeeId=56»

‘the NoMatch property is set to True, if no matched record is found:
If Not recSet.NoMatch Then

‘modifying a DAO recordset — edit a record in a table, using the Edit method (of the Recordset object):

With recSet

.Edit

.Fields(«FirstName») = «James»

.Fields(«SurName») = «Bond»
‘will save only after Update method is run:

.Update

‘Using the LastModified property returns a Bookmark pointing to the most recent added / modified record. This makes the new record as the current record.

.Bookmark = .LastModified

End With

Else

MsgBox «No Matching Record Found!»

‘returns James, refer Image 6b after running this code:
MsgBox recSet.Fields(«FirstName»)

‘———————
‘FIND RECORD WHICH YOU WANT TO DELETE:
‘refer Image 6c after running below code:

recSet.FindFirst «EmployeeId=56»

‘modifying a DAO recordset — delete a record in a table, using the Delete method (of the Recordset object):

‘record with EmployeeId 56 is deleted, refer Image 6c:

If recSet.NoMatch = False Then

recSet.Delete

Else

MsgBox «Record Not Found»

End If
 

‘no current record after the Delete method is used, hence go to First Record:
recSet.MoveFirst
‘returns Tracy, refer Image 6c:
MsgBox recSet.Fields(«FirstName»)

‘go to the Last Record, then go back one record:

With recSet

.MoveLast

.Move -1

‘returns Jim, refer Image 6c:

MsgBox recSet.Fields(«FirstName»)

‘—————
‘close the objects:
recSet.Close
daoDB.Close

‘destroy the variables:
Set daoDB = Nothing

End Sub

Example 7: Use the DAO Recordset.Filter Property to Filter Records (applicable to dynaset–type, snapshot–type, or forward–only–type Recordsets).

Refer Images 7a & 7b, as mentioned in the code.

Sub AccessDAO_RecordsetFilter_7()
‘Filter Records: Use the DAO Recordset.Filter Property to determine inclusion of records in a Recordset opened thereafter. A Filter can be applied to dynaset–type, snapshot–type, or forward–only–type Recordsets.

‘To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host application) by clicking Tools-References in VBE.

Dim strMyPath As String, strDBName As String, strDB As String
Dim daoDB As DAO.Database
Dim recSet As DAO.Recordset, recSetF As DAO.Recordset

‘—————
‘your data source with which to establish connection — ENTER the MS Access Database Name:
strDBName = «SalesReport.accdb»
‘get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
‘set the string variable to the Database:
strDB = strMyPath & «» & strDBName

‘—————
‘assign the database reference to an object variable:
Set daoDB = DBEngine.Workspaces(0).OpenDatabase(strDB)

‘set values of all records in NewJoinee? field (Boolean) to False:
‘refer Image 7a to view the SalesManager Table in MS Access file «SalesReport.accdb», after running below code.
Set recSet = daoDB.OpenRecordset(«SalesManager»)

Do While Not recSet.EOF

recSet.Edit

recSet.Fields(«NewJoinee?»).Value = False

recSet.Update

recSet.MoveNext

recSet.Close
Set recSet = Nothing

‘—————
‘create a filtered Recordset (dynaset–type) with an SQL statement, returning records from SalesManager Table whose Employee Id is between 15 and 56, returning/sorting them in the order of JoinDate:
Set recSet = daoDB.OpenRecordset(«SELECT * FROM SalesManager WHERE EmployeeId BETWEEN 15 AND 56 ORDER BY JoinDate»)

‘refilter the recordset using the Filter property, returning records whose JoinDate is post «01/01/2011» and mark them as NewJoinee:
recSet.Filter = «JoinDate BETWEEN #01/01/2011# AND Now»
‘create another filtered Recordset (dynaset–type), using the DAO Recordset.OpenRecordset Method:
Set recSetF = recSet.OpenRecordset

‘return the EmployeeId & JoinDate fields of each record in the filtered Recordset:

‘refer Image 7b to view the SalesManager Table, after running below code.

Do While Not recSetF.EOF

MsgBox recSetF.Fields(«EmployeeId») & «, » & recSetF.Fields(«JoinDate»)

‘set values of filtered records in NewJoinee? field to True:

recSetF.Edit

recSetF.Fields(«NewJoinee?»).Value = True

recSetF.Update

recSetF.MoveNext

‘—————
‘close the objects:
recSet.Close
daoDB.Close

‘destroy the variables:
Set daoDB = Nothing
Set recSet = Nothing

End Sub

VBA, Open Access Database From Excel

Sep 02, 2015 in Access

In this article I will explain how you can open an existing Access database from Excel using VBA.

If you wish to only import the data into excel you could use the topic covered in the article below:

  • Excel Connect To External Data (Access Database )

In order to create a blank access database from excel using VBA, please see the article below:

  • VBA, Create New Access Database From Excel

Similar to the what was mentioned in the article VBA, Create New Access Database From Excel there are 2 method for automating an Access database:

  1. Early binding
  2. Late binding

In the first method we add reference to the Access Object Library, before execution. It will run faster and we will have access to the VBA editor intellisense. On the other hand there is always the risk of compatibility issues arising when the program is run on a computer with a different version of Access installed. For more information about early vs late binding please see the link below:

  • Microsoft MSDN: Early and Late Binding (Visual Basic)

Note: Although this code was written in VBA for Excel, it is applicable to all other office applications.


Open Existing Access Database:

The codes below will open the access database located in the path “D:StuffBusinessTemp” under the name “NewDB.accdb”:

Late Binding:

Sub Example1()
'Access object
Dim appAccess As Object

'create new access object
Set appAccess = CreateObject("Access.Application")
'open the acces project
Call appAccess.OpenCurrentDatabase( _
"D:StuffBusinessTempNewDB.accdb")
appAccess.Visible = True
End Sub 

Early Binding:
In early binding you will need to add reference to the Access Object Library before running the code. This can be done in the VBA editor (Tools>>Reference):
Microsoft Access Object Library

Note: I have the Microsoft Access 14.0 Object Library installed on my computer. There might be a different version installed the computer you are using. This will not affect the result of the code.

Sub Example2()
'Access object
Dim appAccess As Access.Application

'create new access object
Set appAccess = New Access.Application
'open the acces project
Call appAccess.OpenCurrentDatabase( _
"D:StuffBusinessTempNewDB.accdb")
appAccess.Visible = True
End Sub

Result:
Result


Running SQL Commands:

SQL statements can be run using the code below:

'SQL Statement
appAccess.CurrentProject.Connection.Execute (strSQL)

Where strSQL is a string with the SQL statement.

The code below will open the access database located in the path “D:StuffBusinessTemp” under the name “NewDB.accdb” and create a new table called “NewTable”:

Sub Example3()
'Access object
Dim appAccess As Access.Application

'create new access object
Set appAccess = New Access.Application
'open the acces project
Call appAccess.OpenCurrentDatabase( _
"D:StuffBusinessTempNewDB.accdb")
'create new table
appAccess.CurrentProject.Connection.Execute ( _
"Create Table NewTable")
End Sub

Result:
NewTable
You can download the file and code related to this article from the link below:

  • Open Access.xlsm

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

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.

2016-01-12 23_46_53-Cortana

  • 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.

2016-01-12 23_47_29-Get External Data - Excel Spreadsheet

  • 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.

2016-01-12 23_48_10-Get External Data - Excel Spreadsheet

  • If your Excel spreadsheet has column headings, make sure to mark the First Row Contains.. check box; then hit Next.

2016-01-12 23_48_57-Import Spreadsheet Wizard

  • Then select each column to modify the field name and data type if needed.
  • Hit Next.

2016-01-12 23_49_36-Import Spreadsheet Wizard

  • 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.

2016-01-12 23_50_05-Import Spreadsheet Wizard

  • 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.

2016-01-12 23_50_37-Import Spreadsheet Wizard

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.

2016-01-12 23_52_52-Get External Data - Excel Spreadsheet

  • 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.

2016-01-12 23_54_55-Import Spreadsheet Wizard

  • 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.

Понравилась статья? Поделить с друзьями:
  • Access экспорт таблиц в word
  • Access экспорт отчета excel
  • Access экспорт в excel по шаблону
  • Access формулы как в excel
  • Access фильтры как в excel