Access to excel connection

Plug into your data

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

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

Excel icon

Create a data connection between Excel and Access

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

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

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

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

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

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

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

Refresh data

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

Forced Refresh

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

Customized Refresh

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

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

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

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

All connected!

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

Подключение из Excel к Access через VBA

Время создания: 10.10.2019 07:05

Текстовые метки: Connect Excel To Access, ADO, Connection, Recordset, Excel-Access, CursorLocation, RecordCount

Раздел: !Закладки — VBA — Access — ADO

Запись: xintrea/mytetra_db_adgaver_new/master/base/1570680318sot44eyn6o/text.html на raw.githubusercontent.com

Подключение из Excel к Access через VBA

Полезная функция по подключению из Excel к Access (предварительно надо подключить библиотеку MS ActiveX Data Objects 2.8 Library, как показано на картинке). Проверено — работает.

VBA Добавление Reference

Public Sub test_db()

ConnectionString = «Provider=Microsoft.ACE.OLEDB.12.0; Data Source=» & ActiveWorkbook.Path & «Database4.accdb; Jet OLEDB:Database;»

Dim con As New ADODB.Connection

con.Open ConnectionString

On Error GoTo not_table

con.Execute («SELECT TOP 1 * FROM Customers»)

con.Close

Exit Sub

not_table:

con.Close

End Sub

https://coderoad.ru/30364090/%D0%A1%D1%87%D0%B5%D1%82%D1%87%D0%B8%D0%BA-%D0%BD%D0%B0%D0%B1%D0%BE%D1%80%D0%BE%D0%B2-%D0%B7%D0%B0%D0%BF%D0%B8%D1%81%D0%B5%D0%B9-%D0%B2%D1%81%D0%B5%D0%B3%D0%B4%D0%B0-%D0%B2%D0%BE%D0%B7%D0%B2%D1%80%D0%B0%D1%89%D0%B0%D0%B5%D1%82-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-1

Вам нужно использовать статический курсор. Для этого вам нужно явно создать объект RecordSet, вот так:

Set objRS = Server.CreateObject(«ADODB.Recordset»)

objRS.CursorLocation = adUseClient

objRS.Open «SELECT * FROM « & viewName & «;», objConn, adOpenStatic,adLockReadOnly, adCmdText

Set objRS = Server.CreateObject(«ADODB.Recordset»)

objRS.CursorLocation = adUseClient

objRS.Open «SELECT * FROM » & viewName & «;», objConn, adOpenStatic,adLockReadOnly, adCmdText

Неявно созданные RecordSets имеют серверные курсоры, что приводит к возвращению значения -1.

Для получения дополнительной информации: http://www.adopenstatic.com/faq/recordcounterror.asp

http://www.adopenstatic.com/faq/recordcounterror.asp

NOTE: click here to see superior alternatives to .RecordCount.

RecordCount returns -1
The use of the ADO Recordset’s .RecordCount property requires either the use of:

  • Static or Keyset server-side cursors or
  • A client-side cursor (which returns a Static cursor)

(Note: some OLEDB Providers will return the correct recordcount with an adOpenDynamic cursor, others will not).

By default Recordsets are opened server-side, and with an adOpenForwardOnly cursor. Attempting to access the .RecordCount property with this type of cursor will return -1.

The easiest way to fix this is to change the cursor type to adOpenStatic. Doing this requires you to explicitly create a recordset object:

Set objRS = Server.CreateObject(«ADODB.Recordset»)
objRS.Open strSQL, objConn, adOpenStatic, adLockReadOnly, adCmdText

Attempting to implicitly create a recordset, eg like this:

Set objRS = objConn.execute(strSQL)

will not work, as the implicitly created recordset will have a default adOpenForwardOnly cursor.

As mentioned above, the alternative method is to use a client-side cursor. The client referred in this case is the OLEDB Cursor Service.

Set objRS = Server.CreateObject(«ADODB.Recordset»)
objRS.CursorLocation = adUseClient
objRS.Open strSQL, objConn,,adLockReadOnly, adCmdText

In order to be able to use server-side cursors and .Recordcount, the Recordset object must support either Approximate Positioning or Bookmarking. There has been discussion on the ActiveServerPages list to the effect that the MS Oracle OLEDB Provider (or earlier versions of this provider) do not support either Approximate Positioning or Bookmarking, hence require client-side cursors in order for .RecordCount to work.

The use of ADO constants requires you to define them. You can get information on doing this here. For more information on the Recordset’s .Open method click here.

Back to FAQ Listing

Skip to content

Connection String Parameters for Excel Data Sources

Connection String Parameters for Excel Data Sources

Connection String Parameters for Excel Data Sources

In the previous article, I discussed how we can treat Excel and text files as if they were a database using DAO, and how we can open them without linking. Because they do not use ODBC drivers, their connection string will be formatted quite differently from what you might be accustomed to seeing for an ODBC connection string. There’s a dearth of documentation on the Excel connection string parameters. This is a best-effort to cover some of the gaps and discuss the ramifications of parameters.

Excel connection string parameters

Even though we have 3 different data source “types”:

  1. Excel 8.0: 97-2003 xls files
  2. Excel 12.0: xlsb files
  3. Excel 12.0 Xml: xlsx files

They all use the same parameters.

Here are the list of parameters:

HDR parameter: Header row

YES: The first row is the header and should become the column names for the “table”/”recordset”
NO: The first row is not treated differently and is just a data. All column names will be named “FN” where “N” is a number starting with 1

IMEX parameter: Import/Export Behavior

This governs how the column data types should be defined, based on the content:
1: If the column contain different data types, treat it as a string. Otherwise, match the column to the best data type.
2: Always match the column to a certain data type based on the sample. That may cause an error in reading when we read a row that contains data that does not match the expected data type.

ACCDB parameter: Indicates that Access is using ACCDB file format?

By default, this is always set ACCDB=YES in an accdb file format. However, omitting it or setting it to NO seems to do nothing. It’s a bit of a mystery. If anyone can share what effect this parameter, post in comment and I’ll update the blog.

DATABASE: Path to the Excel workbook

The parameter should contain a fully qualified path, including the workbook’s name.

Minimum working connection string

Note that the DATABASE is the only mandatory parameter in addition to the data type source keyword. Therefore a minimum working connection string can be:

Excel 8.0;DATABASE=C:LinksProducts.xls

Specifying sheet or range in connection string

In the previous sample, you saw that a sheet represented a “DAO.TableDef“. However, worksheets aren’t the only thing that can be a “Tabledef“. If the Excel spreadsheet contains a named range, the named range will be reported as a “Tabledef” as well. Additionally, we can “query” an arbitrary block in the sheet using cell address. For example:

Dim db As DAO.Database
Dim rs As DAO.Recordset

Set db = DBEngine.OpenDatabase(vbNullString, False, False, "Excel 12.0 Xml;HDR=YES;IMEX=2;ACCDB=YES;DATABASE=C:LinksProducts.xlsx")
Set rs = db.OpenRecordsset("Sheet$1A1:A3")

Debug.Print rs.Name, rs.Fields.Count

It’s important to note that the cell addresses cannot exceed the sheet’s used range. For example, the Products.xlsx only actually has contents in A1:B3, that means if you open a recordset using Sheet1$A1:D5, you still get only 2 for fields count and 3 for record count. The extra blank columns/rows are simply ignored. On the flip side, if you dirtied a cell somewhere outside the A1:B3, the sheet’s UsedRange will be now as bigger and querying would then include blank columns and rows.

Therefore those are valid names to use in a query on a Excel “database”:

  1. Sheet1$ – Entire used range of a worksheet.
  2. Sheet1$A1:B4 – Only 2 columns and 3 rows (not counting header), providing that the contents are filled. Otherwise columns or rows may be less than requested.
  3. ProductsRange – the named range with that name.

I find it much nicer to use named ranges where practical as this ensure that you are not hard-coding the addresses in your code especially if the range gets moved around due to user inserting new columns or rows but not altering the contents of the named range. However it is not always practical, especially if you are receiving spreadsheets from a 3rd party and therefore have no control over its contents or formats. In this case, writing a SQL query can work, too.

Querying Excel data source

Suppose we can’t control the format and we don’t want to rely on absolute address even though we are confident that certain columns and rows will be in fact present. In that situation, the best thing to do is to query. Here’s an example that select only one row:

  Dim db As DAO.Database
  Set db = DBEngine.OpenDatabase(vbNullString, False, False, "Excel 12.0 Xml;HDR=YES;IMEX=2;ACCDB=YES;DATABASE=C:LinksProducts.xlsx")

  Dim rs As DAO.Recordset
  Set rs = db.OpenRecordset("SELECT d.[Count] FROM [Sheet1$] AS d WHERE d.[Products] = 'Bananas';")
  Debug.Print rs.Fields(0).Value

Hopefully you can see this is much easier than iterating over each rows to find which one has “Bananas” and then reading the column to right to get the count. In this case, querying beats out automating Excel.

Conclusion

You’ve seen that DAO makes it very easy for us to work with Excel data source and pretend as if it was a relational data source and use our favorite querying language and familiar DAO objects instead of writing bunch of VBA code automating Excel to find the data we want. The connection string parameters are fairly straightforward and as long you have the path, you’re good for linking or opening an Excel spreadsheet.

In the next article we will look at text file connection parameters.

Spread the knowledge!

Comments are closed.

Page load link

Go to Top

How to Connect Access Database in Excel Macros?

Updating Excel Spreadsheet from Access Database using this step by step Excel VBA Access Macro code is just that simple. We are going to use a ADODB connection in this sample code.

Just copy paste this Excel VBA Access MDB conenction code to your VBA Project.

Excel To Access Connection – Simplest Code

Just change these two things in the code. It is enough for this to work better.

  1. Database path – sDBPath : This should have the exact folder path & MDB Access file name that is being accessed with this code.
  2. Query String – sQuery : The SQL query in this variable should match the Database Table & the fields exactly as how it is defined in the MDB database.

Once these two fields are edited, then this code will perfectly fine in a Excel VB Editor.

'--------------------------------------------------------------------------------
'Code by author@officetricks.com (or) kumarapush777 (Fiverr)
'Visit https://officetricks.com to get more Free & Fully Functional VBA Codes
'--------------------------------------------------------------------------------
Sub VBA_Connect_To_MDB_ACCESS()

    'Make Reference to Microsoft AxticX Data Objects Library
    Dim dbConn As ADODB.Connection, dbRecSet As ADODB.Recordset
    Dim sConnString As String, sQuery As String
    Dim sDBPath As String
    
    'Define MDB ACCESS file path
    sDBPath = "D:OfficeTricksSalesOrders.accdb"
    
    'SQL Query String
    sQuery = "SELECT CustomerID, CustFirstName , CustLastName from Customers;"
    
    'ADODB Conenction String to initiate connection with MDB ACCESS
    sConnString = "Provider=Microsoft.ace.OLEDB.12.0; Data Source=" & sDBPath & ";"
    
    'Open Connection
    Set dbConn = New ADODB.Connection
    dbConn.Open ConnectionString:=sConnString
    
    'Execute SQL Query & Get Records matching the query to recordset
    Set dbRecSet = New ADODB.Recordset
    dbRecSet.Open Source:=sQuery, ActiveConnection:=dbConn
    
    'If Query Returned Values, Read them one by one
    If (dbRecSet.RecordCount <> 0) Then
        Do While Not dbRecSet.EOF
            MsgBox dbRecSet.Fields(1).Value
            dbRecSet.MoveNext
        Loop
    End If
    
    'Close Connection & RecordSet
    Set dbRecSet = Nothing
    dbConn.Close
    Set dbConn = Nothing
End Sub

Make sure that the MDB database Table has correct field names as specified in the query. Also it has enough data.

Note: Before executing this code, from your VB Edifor go to Tools in the menu -> References & add a reference to “Microsoft ActiveX Data Objects Library”. This is to make sure that ADODB object can be created from within the VBA Macro code.

The loop after that is present after the recordset.open command will get records from the table one by one, till end of the table. Make sure the replace the msgbox command with some assignment. If not you will end up in giving too many ‘OK’ clicks for the message box that pops up for every record fetch.

Apart from recordset.Movenext, there are other commands available to move the cursor or current position to First or last record or to any desired point as well.

In the next tutorial, we will see how to query Access database & load them to a list box in userform.

Import or Export Data from Access to Excel using ADO

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

Part 3 of 4


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

1. Microsoft Access: ActiveX Data Objects Library (ADO).

2. Microsoft Access: Use ADO to Execute SQL statements.

3. Import or Export Data from Access to Excel using ADO.

4. Microsoft Access: ActiveX Data Objects Extensions (ADOX).

—————

Also Read:

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


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

Contents:

Use ADO to Import Data from Microsoft Access Database to Excel

Use ADO to Import data from an Access Database Table to an Excel worksheet (your host application)

Use ADO to Export data from Excel worksheet (your host application) to Access Database Table

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

Use ADO to Import Data from Microsoft Access Database to Excel

In this section we show, with the help of practical examples, how to connect to Access Database from Excel (your host application) using ADO to: (i) import or retrieve data from Access database to Excel worksheet; and (ii) Export data from Excel worksheet to Access Database Table.

Range.CopyFromRecordset Method: This method is commonly used to copy records from an Aceess Table to an Excel worksheet. Syntax: Range.CopyFromRecordset(Data, MaxRows, MaxColumns).

Range is the worksheet range to which the records are copied, starting at its upper-left corner. Data is the Recordset (ie. set of records) in the Access database to be copied and the current row in the Recordset is the starting record from where copying begins. MaxRows and MaxColumns refer to the maximum numbers of rows (ie. records) and fields respectively to be copied and omitting these arguments will indicate that all rows and fields are copied. Data is mandatory to specify while other arguments of MaxRows and MaxColumns are optional.

Example 9: Using ADO to Import data from an Access Database Table to an Excel worksheet (your host application).

Refer to Images 9a, 9b, 9c, 9d and 9e as mentioned in the code.

The code is simple to understand, though apparantly long due to multiple options shown (reference to images 9a to 9e) as to how data can be imported into Excel. Each option can be treated as a separate code and run accordingly.

Sub automateAccessADO_9()
‘Using ADO to Import data from an Access Database Table to an Excel worksheet (your host application).
‘refer Image 9a to view the existing SalesManager Table in MS Access file «SalesReport.accdb».

‘To use ADO in your VBA project, you must add a reference to the ADO Object Library in Excel (your host application) by clicking Tools-References in VBE, and then choose an appropriate version of Microsoft ActiveX Data Objects x.x Library from the list.

‘—————
‘DIM STATEMENTS

Dim strMyPath As String, strDBName As String, strDB As String, strSQL As String
Dim i As Long, n As Long, lFieldCount As Long
Dim rng As Range

‘instantiate an ADO object using Dim with the New keyword:
Dim adoRecSet As New ADODB.Recordset
Dim connDB As New ADODB.Connection

‘—————
‘THE CONNECTION OBJECT

strDBName = «SalesReport.accdb»
strMyPath = ThisWorkbook.Path
strDB = strMyPath & «» & strDBName

‘Connect to a data source:
‘For pre — MS Access 2007, .mdb files (viz. MS Access 97 up to MS Access 2003), use the Jet provider: «Microsoft.Jet.OLEDB.4.0». For Access 2007 (.accdb database) use the ACE Provider: «Microsoft.ACE.OLEDB.12.0». The ACE Provider can be used for both the Access .mdb & .accdb files.
connDB.Open ConnectionString:=«Provider = Microsoft.ACE.OLEDB.12.0; data source=» & strDB

‘—————
‘OPEN RECORDSET, ACCESS RECORDS AND FIELDS

Dim ws As Worksheet
‘set the worksheet:
Set ws = ActiveWorkbook.Sheets(«Sheet8»)

‘Set the ADO Recordset object:
Set adoRecSet = New ADODB.Recordset

‘Opening the table named SalesManager:
strTable = «SalesManager»

‘—————
‘COPY RECORDS FROM ALL FIELDS USING CopyFromRecordset:
‘refer Image 9b to view records copied to Excel worksheet

‘open recordset/table:
adoRecSet.Open Source:=strTable, ActiveConnection:=connDB, CursorType:=adOpenStatic, LockType:=adLockOptimistic

Set rng = ws.Range(«A1»)
lFieldCount = adoRecSet.Fields.count

For i = 0 To lFieldCount — 1

‘copy column names in first row of the worksheet:
rng.Offset(0, i).Value = adoRecSet.Fields(i).Name

Next i

‘copy record values starting from second row of the worksheet:
rng.Offset(1, 0).CopyFromRecordset adoRecSet
‘to copy 4 rows and 3 columns of the recordset to excel worksheet:
‘rng.Offset(1, 0).CopyFromRecordset Data:=adoRecSet, MaxRows:=4, MaxColumns:=3

‘select a column range:
Range(ws.Columns(1), ws.Columns(lFieldCount)).AutoFit
‘worksheet columns are deleted because this code is only for demo:
Range(ws.Columns(1), ws.Columns(lFieldCount)).Delete

adoRecSet.Close

‘—————
‘COPY RECORDS FROM SELECTED FIELDS USING CopyFromRecordset:
‘refer Image 9c to view records copied to Excel worksheet

‘copy all records from the selected fields (EmployeeId, FirstName & JoinDate):
strSQL = «SELECT EmployeeId, FirstName, JoinDate FROM SalesManager WHERE EmployeeId > 15″
adoRecSet.Open Source:=strSQL, ActiveConnection:=connDB, CursorType:=adOpenDynamic, LockType:=adLockOptimistic

Set rng = ws.Range(«A1»)
lFieldCount = adoRecSet.Fields.count

For i = 0 To lFieldCount — 1

‘copy column names in first row of the worksheet:

rng.Offset(0, i).Value = adoRecSet.Fields(i).Name

Next i

‘copy record values starting from second row of the worksheet:
rng.Offset(1, 0).CopyFromRecordset adoRecSet

‘select a column range:
Range(ws.Columns(1), ws.Columns(lFieldCount)).AutoFit
‘worksheet columns are deleted because this code is only for demo:
Range(ws.Columns(1), ws.Columns(lFieldCount)).Delete

adoRecSet.Close

‘—————
‘COPY RECORDS FROM ALL FIELDS OF A RECORDSET:
‘refer Image 9d to view records copied to Excel worksheet

adoRecSet.Open Source:=strTable, ActiveConnection:=connDB, CursorType:=adOpenStatic, LockType:=adLockOptimistic

Set rng = ws.Range(«A1»)
lFieldCount = adoRecSet.Fields.count

For i = 0 To lFieldCount — 1

‘copy column names in first row of the worksheet:
rng.Offset(0, i).Value = adoRecSet.Fields(i).Name
adoRecSet.MoveFirst

 ‘copy record values starting from second row of the worksheet:

n = 1

Do While Not adoRecSet.EOF

rng.Offset(n, i).Value = adoRecSet.Fields(i).Value
adoRecSet.MoveNext

n = n + 1

Loop

Next i

‘select column range to AutoFit column width:
Range(ws.Columns(1), ws.Columns(lFieldCount)).AutoFit
‘worksheet columns are deleted because this code is only for demo:
Range(ws.Columns(1), ws.Columns(lFieldCount)).Delete
adoRecSet.Close

‘—————
‘COPY RECORDS FROM SELECTED FIELDS OF A RECORDSET:
‘refer Image 9e to view records copied to Excel worksheet

‘copy all records from the 3 fields of EmployeeId, SurName, JoinDate:
strSQL = «SELECT EmployeeId, SurName, JoinDate FROM SalesManager»
adoRecSet.Open Source:=strSQL, ActiveConnection:=connDB, CursorType:=adOpenDynamic, LockType:=adLockOptimistic

Set rng = ws.Range(«A1»)
lFieldCount = adoRecSet.Fields.count

For i = 0 To lFieldCount — 1

‘copy column names in first row of the worksheet:
rng.Offset(0, i).Value = adoRecSet.Fields(i).Name
adoRecSet.MoveFirst

‘copy record values starting from second row of the worksheet:

n = 1

Do While Not adoRecSet.EOF

rng.Offset(n, i).Value = adoRecSet.Fields(i).Value
adoRecSet.MoveNext

n = n + 1

Loop

Next i

‘select a column range:
Range(ws.Columns(1), ws.Columns(lFieldCount)).AutoFit
‘worksheet columns are deleted because this code is only for demo:
Range(ws.Columns(1), ws.Columns(lFieldCount)).Delete

adoRecSet.Close

‘—————
‘close the objects
connDB.Close

‘destroy the variables
Set adoRecSet = Nothing
Set connDB = Nothing

End Sub

Example 10: Using ADO to Export data from Excel worksheet (your host application) to Access Database Table.

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

Sub automateAccessADO_10()
‘Using ADO to Export data from Excel worksheet (your host application) to an Access Database Table.
‘refer Image 10a to view the existing SalesManager Table in MS Access file «SalesReport.accdb»
‘refer Image 10b for data in Excel worksheet which is exported to Access Database Table.
‘refer Image 10c to view the SalesManager Table in Access file «SalesReport.accdb», after data is exported.

‘To use ADO in your VBA project, you must add a reference to the ADO Object Library in Excel (your host application) by clicking Tools-References in VBE, and then choose an appropriate version of Microsoft ActiveX Data Objects x.x Library from the list.

‘—————
‘DIM STATEMENTS

Dim strMyPath As String, strDBName As String, strDB As String, strSQL As String
Dim i As Long, n As Long, lastRow As Long, lFieldCount As Long

‘instantiate an ADO object using Dim with the New keyword:
Dim adoRecSet As New ADODB.Recordset
Dim connDB As New ADODB.Connection

‘—————
‘THE CONNECTION OBJECT

strDBName = «SalesReport.accdb»
strMyPath = ThisWorkbook.Path
strDB = strMyPath & «» & strDBName

‘Connect to a data source:
‘For pre — MS Access 2007, .mdb files (viz. MS Access 97 up to MS Access 2003), use the Jet provider: «Microsoft.Jet.OLEDB.4.0». For Access 2007 (.accdb database) use the ACE Provider: «Microsoft.ACE.OLEDB.12.0». The ACE Provider can be used for both the Access .mdb & .accdb files.
connDB.Open ConnectionString:=«Provider = Microsoft.ACE.OLEDB.12.0; data source=» & strDB

‘—————
‘OPEN RECORDSET, ACCESS RECORDS AND FIELDS

Dim ws As Worksheet
‘set the worksheet:
Set ws = ActiveWorkbook.Sheets(«Sheet9»)

‘Set the ADO Recordset object:
Set adoRecSet = New ADODB.Recordset

‘Opening the table named SalesManager:
strTable = «SalesManager»
adoRecSet.Open Source:=strTable, ActiveConnection:=connDB, CursorType:=adOpenStatic, LockType:=adLockOptimistic

‘—————
‘COPY RECORDS FROM THE EXCEL WORKSHEET:
‘Note: Columns and their order should be the same in both Excel worksheet and in Access database table

lFieldCount = adoRecSet.Fields.count
‘determine last data row in the worksheet:
lastRow = ws.Cells(Rows.count, «A»).End(xlUp).Row

‘start copying from second row of worksheet, first row contains field names:

For i = 2 To lastRow

adoRecSet.AddNew

For n = 0 To lFieldCount — 1

adoRecSet.Fields(n).Value = ws.Cells(i, n + 1)

Next n

adoRecSet.Update

Next i

‘—————
‘close the objects
adoRecSet.Close
connDB.Close

‘destroy the variables
Set adoRecSet = Nothing
Set connDB = Nothing

End Sub

Понравилась статья? Поделить с друзьями:
  • Access not importing excel file
  • Access meaning of the word
  • Access keys in excel
  • Access import from excel vba
  • Access help in word