What is recordset in excel vba

DatabaseVisual Basic for Applications or VBA is an important event driven programming language.  It is used for creating programs which enhance the Microsoft Office suite of applications. Visual Basic for Applications is perfect for developing specific applications, whether these are office resources, graphics programs, file sorting programs, or any other kind of Windows-based software programs. Today we look at the useful and frequently used Recordset function, in this intermediate level tutorial. You require a basic level of familiarity with Microsoft Access. If you’re new to them, you should first do this introductory course to Microsoft Access.  For folks who are familiar with VBA, you can just do a quick brush up with this VBA tutorial.

What is Recordset

A recordset is a structure which stores a group of records in a database. These records could be the result of a query or the contents of an individual table. Modifying the information stored in record sets does not affect the corresponding information contained in the actual database tables. Recordsets are widely employed as an integral part of database programming which includes Visual Basic for Applications.

Note that recordset is a blank table which is fully customizable with infinite rows and columns. These include whatever information a computer’s database returns, no matter how small or large. Good databases have the ability to generate and display recordsets. You can learn more about managing databases in Excel in this course.

Microsoft Office Access, a database, permits you to use VBA to create applications in Access. VBA is usually used to automate repetitive tasks in MS Office applications. MS Access is a relational database system generally used for smaller databases. A select query retrieves data from a database table. A recordset reads the content returned by the query. Here we look at a program to create a table and view its content using a select query. You can take this course from Udemy to learn more about using VBA with MS Access.

Example 1: How to use recordset in a query

Sub useRecordset()
Dim strSQL1 As String
Dim dbs1 As Database
Dim rst1 As Recordset
Dim tmpStr As String
Set dbs = CurrentDb
tmpStr = "Company | Last Name | "
tmpStr = tmpStr& "First Name | "
tmpStr = tmpStr& "Job Title | "
tmpStr = tmpStr& "Business Phone"
Debug.PrinttmpStr
strSQL1 = "SELECT Customers.Company, Customers.[Last Name], "
strSQL1 = strSQL1& "Customers.[First Name], "
strSQL1 = strSQL1& "Customers.[Job Title], Customers.[Business Phone]"
strSQL1 = strSQL1& "FROM Customers;"
Set rst1 = dbs1.OpenRecordset(strSQL)
rst1.MoveLast
rst1.MoveFirst
Do While Not rst1.EOF
tmpStr = rst1.Fields(0).Value
tmpStr = tmpStr& " | " & rst1.Fields(1).Value
tmpStr = tmpStr& " | " & rst1.Fields(2).Value
tmpStr = tmpStr& " | " & rst1.Fields(3).Value
tmpStr = tmpStr& " | " & rst1.Fields(4).Value
Debug.PrinttmpStr
Rst1.MoveNext
Loop
rst1.Close
dbs1.Close

In this program, declare the variables dbs1 as database object, rst1 as recordset object. Use SQL select command to the query the customer’s table. Open the recordset using the query. Loop through the recordset and display the records till the end of the recordset. In the end, close the database and the recordset objects.

Example 2: VBA Recordset to run a select Query

Private Sub runSelectQuery()
Dim db1 As Database
Dim rcrdSe1t As Recordset
Dim strSQL1 As String
Dim Xcntr1As Integer
Set db1 = CurrentDb
strSQL1 = "CREATE TABLE selectQueryData (NumField NUMBER, Tenant TEXT, Apt TEXT);"
DoCmd.RunSQL (strSQL1)
strSQL1 = "INSERT INTO selectQueryData (NumField, Tenant, Apt)”
strSQL1 = strSQL1& "VALUES (1, 'John', 'A');"
DoCmd.SetWarnings False
DoCmd.RunSQL (strSQL1)
strSQL1 = "INSERT INTO selectQueryData (NumField, Tenant, Apt) "
strSQL1 = strSQL1& "VALUES (2, 'Susie', 'B');"
DoCmd.SetWarnings False
DoCmd.RunSQL (strSQL1)
strSQL1 = "INSERT INTO selectQueryData (NumField, Tenant, Apt) "
strSQL1 = strSQL1& "VALUES (3, 'Luis', 'C');"
DoCmd.SetWarnings False
DoCmd.RunSQL (strSQL1)
strSQL1 = "Select selectQueryData.* from selectQueryData "
strSQL1 = strSQL1& "WHERE selectQueryData.Tenant = 'Luis';"
Set rcrdSet1 = db.OpenRecordset(strSQL1)
rcrdSet1.MoveLast
rcrdSet1.MoveFirst
For Xcntr = 0 To rcrdSet1.RecordCount - 1
MsgBox "Tenant: " &rcrdSet.Fields("Tenant").Value & ", Lives in apt: " & _
rcrdSet1.Fields("Apt").Value
rcrdSet1.MoveNext
Next Xcntr
rcrdSet1.Close
db.Close
End Sub

In this program, we declare the variables Db1 as database object, rcrdSet1 as recordset object, strSQL1 as string object and Xcntr as Integer.The string object is assigned a query string.  DoCmd.RunSQL is a command which runs the string to create a table. A new table is created. Insert SQl command is used to insert records in the table. The recordset is opened and we move to the first record in the recordset. Display each record in the recordset until we reach the last record of the recordset. In the end we close both the recordset object and the database object.

Example 3: Program to Set the Value of a Specific Record

Dim sqlStr1 As String
Dim rst1 As Recordset
Dim dbs1 As Database
Set dbs1 = CurrentDb
sQLString = "CREATE TABLE editRecord (F_Name TEXT, L_Name TEXT)"
DoCmd.SetWarnings False
DoCmd.RunSQL (sQLString)
Strsql1 = "INSERT INTO editRecordVALUES('JOhn','Smith')"
DoCmd.RunSQL (strsql1)
strsql = "INSERT INTO editRecord VALUES('George','Bailey')"
DoCmd.RunSQL (strsql1)
strsql = "INSERT INTO editRecord VALUES('Glen','Maxwell')"
DoCmd.RunSQL (strsql1)
Set rst1 = dbs.OpenRecordset("SELECT editRecord.* FROM editRecord")
Set rst1 = dbs.OpenRecordset("SELECT editRecord.* FROM editRecord")
rst1.Move (2)
rst1.Edit
rst1.Fields("F_Name").Value = "PAUL"
rst1.Update
rst1.Close
Set dbs = Nothing

In this program, we declare sqlStr1 as string variable, rst1 as recordset object and dbs1 as database object. A new table is created using the DoCmd.RunSQL command. Three records are inserted into the table. A recordset is created by querying the table for allits records.We move through the record set to the record number 3 and update the “F_name” field to “Paul.” Then close the recordset. Press “F5” Functional key to run the subroutine.  You may want to learn more about Microsoft Access with this course to understand these examples better.

Example 4:  Search for Records in a Table

Sub searchRecords()
Dim rst1 As Recordset
Dim dbs1 As Database
Dim stringToSearch1 As String
Set dbs1 = CurrentDb
stringToSearch1 = "Dyna"
Set rst1 = dbs1.OpenRecordset("SELECT Customers.* FROM Customers")
Set rst1 = dbs1.OpenRecordset("SELECT <table name>.* FROM <table name>")
Rst1.MoveFirst
Do While Not rst1.EOF
If rst1.Fields("First Name").Value = stringToSearch1 Then
MsgBox "Found "&stringToSearch& " in record number: " & rst1.AbsolutePosition
rst1.MoveLast
Else
Rst1.MoveNext
End If
Loop
stringToSearch1 = "<your text to search>"
If rst1.Fields("<your column name>").Value = stringToSearch Then
rst1.Close
dbs1.Close

In the program, we declare the variables rst1 as Recordset object and  dbs1 as database object. Create a recordset by querying the customer’s table. Move to the first record of the recordset. Loop through the recordset by incrementing recordset position and search for “Dyna” in the first name column.  After the record is found, close the recordset and database objects. This course on using VBA with Microsoft Access has many more examples you may want to try out.

Example 5: How to copy from a recordset into a Table

Sub RecordsetExample()
Dim dbTest1 as Database
Dim rsRecordset1 as Recordset
Dim sqlStatement1 as String
Set dbTest1 = OpenDatabase("MyDatabase.mbd")
set rsRecordset1 = .OpenRecordset("Table1",dbOpenTable)
End With
sqlStatement1 = "INSERT INTO Table2 VALUES" & rsRecordset1
With rsRecordset1
rsRecordset1.MoveFirst
Do
rsRecordset1.RunSQL(sqlStatement1)
rsRecordset1.MoveNext
Loop While Not rsRecordset1.EOF
End With
End Sub

Declare the variables dbTest1, rsRecordset1,sqlStatement1 as type database, recordset and string objects respectively. Open the recordset object read the records and inserts the values into the database table. This operation terminates reaching the end of the recordset. In the end close the database and recordset objects.

Example 6:How to Use VBA to Import Data From Excel Into Access

Sub importExcelData()
Dim xlApp As Excel.Application
Dim xlBk As Excel.Workbook
Dim xlSht As Excel.Worksheet
Dim dbRst1 As Recordset
Dim dbs1 As Database
Dim SQLStrAs String
Set dbs1 = CurrentDb
Set xlApp = Excel.Application
Set xlBk = xlApp.Workbooks.Open("C:TempdataToImport.xlsx")
Set xlSht = xlBk.Sheets(1)
SQLStr = "CREATE TABLE excelData(columnOne TEXT, columnTwo TEXT)"
DoCmd.SetWarnings False
DoCmd.RunSQL (SQLStr)
Set dbRst1 = dbs.OpenRecordset("excelData")
dbRst1.AddNew
xlSht.Range("A2").Select
dbRst1.Fields(0).Value = xlSht.Range("A2").Value
xlSht.Range("B2").Select
dbRst1.Fields(1).Value = xlSht.Range("B2").Value
dbRst1.Update
dbRst1.Close
dbs1.Close
xlBk.Close
End Sub

In the beginning, we declare xlApp, xlBk and xlSht as variables you will use to read Excel. Also, we declare the variables dbrst1 as recordset object and dbs1 as database object. Use DoCmd.RunSQL to execute an SQL command. We get values from the Excel workbook, save them to your table and update the records. In the end always remember to close  the database and recordset objects. If you’d like a more hands on approach, you can check out this course on MS Access.

Hope you had fun learning the Recordset function. Programming is best learnt by creating your own programs. Go through the examples above and play with the code. Once you’re ready to move it up to the next level, you can take this advanced VBA course for Microsoft Access by Simon Sez. It has a lot more juice and tips to make your work with MS Access so much more easier!

What is a Recordset in VBA?

What purpose does it serve?

How do you use them?

SteveC's user avatar

SteveC

15.5k23 gold badges99 silver badges173 bronze badges

asked Feb 26, 2010 at 1:40

Alan_AI's user avatar

This is quite a large question. Briefly, a recordset is a selection of records from a table or query. Depending on the query used, it can be used to add, edit, delete and manipulate records. A recordset can be obtained using ADO or DAO and may have different methods and properties accordingly. Sticking to DAO, which is native to Access:

Dim rs As DAO.Recordset
Set rs=CurrentDB.OpenRecordset("Select ID, Company From Companies")
rs.Edit
rs!Company="ABC"
rs.Update

rs.AddNew
rs!Company="ABC"
rs.Update

Do While Not rs.EOF
   If rs!Company="ABC" Then
      ''Do something
   End If
   rs.MoveNext
Loop

Set rs=Forms!SomeForm.RecordsetClone
rs.FindFirst "Company='ABC'"
If Not rs.NoMatch Then
   Forms!SomeForm.Bookmark=rs.Bookmark
End If

answered Feb 26, 2010 at 1:48

Fionnuala's user avatar

FionnualaFionnuala

90.1k7 gold badges110 silver badges148 bronze badges

A recordset is basically an in-memory container for data. You use it to manipulate data, or to pass data around.

When you read data from the database in VBA, the result will be in a recordset (with the exception of scalar data).

answered Feb 26, 2010 at 1:47

Gabriel McAdams's user avatar

Gabriel McAdamsGabriel McAdams

56.4k12 gold badges61 silver badges76 bronze badges

Gabriel gave an excellent description of a recordset.

Databases are built to use set theory to interact with the data, but a recordset is a way to also work with the data procedurally. This code looks more like programming. The «MoveNext» method is an example where you can step through the data and work with one record one at a time.

See Remou’s code to implement DAO recordsets.

answered Feb 26, 2010 at 2:50

JeffO's user avatar

JeffOJeffO

7,8773 gold badges44 silver badges53 bronze badges

Содержание

  1. Объект Recordset (DAO)
  2. Комментарии
  3. Пример
  4. Объект Recordset (ADO)
  5. Замечания

Объект Recordset (DAO)

Применяется для: Access 2013, Office 2013

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

Комментарии

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

Объект Recordset табличного типа — представление в коде базовой таблицы, которое вы можете использовать для добавления, изменения и удаления записей из таблицы одной базы данных (только для рабочей области Microsoft Access).

Объект Recordset типа Dynaset — результат запроса, который может обновлять записи. Объект Recordset типа Dynaset является динамическим набором записей, которые можно использовать для добавления, изменения и удаления записей из базовой таблицы базы данных или таблиц. Объект Recordset типа Dynaset может содержать поля из одной или нескольких таблиц в базе данных. Этот тип соответствует курсору набор ключей ODBC.

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

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

Динамический тип объекта Recordset — набор результатов запроса, получаемый из одной или нескольких базовых таблиц, в котором вы можете добавить, изменить или удалить записи из возвращающего строку запроса. Кроме того, записи, которые добавляют, удаляют или изменяют другие пользователи в базовой таблице, также будут отображаться в вашем объекте Recordset. Этот тип соответствует динамическому курсору ODBC (только для рабочих областей ODBCDirect).

Рабочие области ODBCDirect не поддерживаются в Microsoft Access 2013. Используйте ADO, если вы хотите получить доступ к внешним источникам данных без использования ядра СУБД Microsoft Access.

Вы можете выбрать тип объекта Recordset, который вы хотите создать, с помощью аргумента типа метода OpenRecordset.

В рабочей области Microsoft Access, если не задан тип, интерфейс DAO пытается создать тип объектаRecordset с наиболее широким набором функций, начиная с табличного. Если этот тип не поддерживается, интерфейс DAO пытается создать объект типа Dynaset, затем моментальный снимок и, наконец, однонаправленный тип объекта Recordset.

В рабочей области ODBCDirect, если не задан тип, интерфейс DAO пытается создать тип объектаRecordset с самой быстрой реакцией на запрос, начиная с однонаправленного типа. Если этот тип не поддерживается, интерфейс DAO пытается создать объект типа мгновенный снимок, затем dynaset и, наконец, динамический тип объекта Recordset.

При создании объекта Recordset с помощью несвязанного объекта TableDef в рабочей области Microsoft Access, создается табличный тип объекта Recordset. Только объекты Recordset динамического типа или типа моментальный снимок могут создаваться со связанными таблицами или таблицами в базах данных ODBC с подключенным ядром СУБД Microsoft Access.

Объект Recordset автоматически добавляется в коллекцию Recordsets при открытии объекта и автоматически удаляется при его закрытии.

Если вы используете переменные для представления объекта Recordset и объекта Database, который содержит объект Recordset, убедитесь, что переменные принадлежат к той же области или имеют то же время существования. Например, если вы объявляете публичную переменную, которая определяет объект Recordset, убедитесь, что переменная, которая представляет Database с Recordset, также является публичной, или объявлена с помощью процедуры Sub или Function с применением ключевого слова Static.

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

Типы Dynaset, моментальный снимок и однонаправленный для объекта Recordset хранятся в локальной памяти. Если в локальной памяти для хранения данных недостаточно места, ядро СУБД Microsoft Access сохраняет дополнительные данные в дисковом пространстве TEMP. Если свободное место заканчивается, возникает перехватываемая ошибка.

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

При создании объекта Recordset текущая запись расположена по направлению к первой записью, если есть какие-либо записи. Если записи отсутствуют, свойство RecordCount имеет значение 0, а свойство BOF и EOF имеют значение ИСТИНА.

Вы можете использовать методы MoveNext, MovePrevious, MoveFirst и MoveLast, чтобы изменить положение текущей записи. Объекты Recordset однонаправленного типа поддерживают только метод MoveNext. При использовании методов перемещения для перехода к каждой записи (или «прогулки» по объекту Recordset), вы можете использовать свойства BOF и EOF, чтобы проверить начало или конец объекта Recordset.

Для объектов Recordset типа dynaset и моментальный список в рабочей области Microsoft Access можно также использовать методы поиска, например FindFirst, чтобы найти определенную запись на основе критериев. Если запись не найдена, свойство NoMatch получает значение ИСТИНА. Для табличного типа объектов Recordset можно сканировать записи, используя метод Seek.

Свойство Type указывает тип созданного объекта Recordset, а свойство Updatable указывает на то, можете ли вы изменить записи объекта.

Сведения о структуре базовой таблицы, например, имена и типы данных каждого объекта Field и любых объектов Index хранятся в объекте TableDef.

Чтобы сослаться на объект Recordset в коллекции по его порядковому номеру или по его свойствуName, используйте любую из следующих синтаксических форм:

Recordsets(0)

Recordsets(«name»)

Наборы записей! [имя]

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

Пример

В этом примере показаны объекты Recordset и коллекция Recordset с помощью открытия четырех разных типов Recordsets, перечисления коллекции Recordsets для текущего объекта Databaseи перечисления коллекции Properties для каждого объекта Recordset.

В этом примере используется методOpenRecordset для открытия пяти разных объектов Recordset и отображения их содержимого. Процедура OpenRecordsetOutput является обязательной для запуска этой процедуры.

В этом примере открывается динамический тип объекта Recordset и перечисляются ее записи.

В этом примере открывается тип dynaset объекта Recordset и отображаются уровни обновления его полей.

В этом примере открывается однонаправленный тип объекта Recordset, демонстрируются характеристики только для чтения и пошаговые инструкции для объекта Recordset и метода MoveNext.

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

В этом примере открывается табличный тип объекта Recordset, задается его свойство Index и перечисляются его записи.

В приведенном ниже примере показано, как использовать метод Seek для поиска записи в связанной таблице.

В приведенном ниже примере показано, как открыть объект Recordset на основании запроса параметра.

В приведенном ниже примере показано, как открыть объект Recordset на основании таблицы или запроса.

В приведенном ниже примере показано, как открыть объект Recordset на основании SQL оператора.

В приведенном ниже примере показано, как использовать методы FindFirst и FindNext для поиска записи в Recordset.

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

Источник

Объект Recordset (ADO)

Область применения: Access 2013, Office 2013

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

Замечания

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

ADODB. Recordset — это идентификатор ProgID, который следует использовать для создания объекта Recordset . Существующие приложения, ссылающиеся на устаревший ADOR. Набор записей ProgID будет продолжать работать без повторной компиляции, но новая разработка должна ссылаться на ADODB. Набора записей.

В ADO определены четыре различных типа курсоров:

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

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

Статический курсор — предоставляет статическую копию набора записей для поиска данных или создания отчетов; всегда разрешает закладки и, следовательно, все типы перемещения по набору записей. Добавления, изменения или удаления другими пользователями не будут видны. Это единственный тип курсора, разрешенный при открытии объекта Recordset на стороне клиента.

Курсор только вперед — позволяет прокручивать набор записей только вперед. Добавления, изменения или удаления другими пользователями не будут видны. Это повышает производительность в ситуациях, когда необходимо выполнить только один проход через набор записей.

Задайте свойство CursorType перед открытием Recordset , чтобы выбрать тип курсора, или передайте аргумент CursorType с помощью метода Open . Некоторые поставщики поддерживают не все типы курсоров. Ознакомьтесь с документацией по поставщику. Если тип курсора не указан, ADO по умолчанию открывает курсор только вперед.

Если для свойства CursorLocation задано значение adUseClient , чтобы открыть набор записей, свойство UnderlyingValue в объектах Field недоступно в возвращенном объекте Recordset . При использовании с некоторыми поставщиками (например, поставщиком ODBC Майкрософт для OLE DB в сочетании с Майкрософт SQL Server) можно создавать объекты Recordset независимо от ранее определенного объекта Connection, передав строку подключения с помощью метода Open. ADO по-прежнему создает объект Connection , но не назначает этот объект переменной объекта. Однако при открытии нескольких объектов Recordset через одно и то же подключение необходимо явно создать и открыть объект Connection . при этом объект Connection назначается переменной объекта . Если эта переменная объекта не используется при открытии объектов Recordset , ADO создает новый объект Connection для каждого нового набора записей, даже если передается одна и та же строка подключения.

При необходимости можно создать столько объектов Recordset .

При открытии набора записей текущая запись размещается в первой записи (если она есть), а свойства BOF и EOF имеют значение False. Если записей нет, параметры свойств BOF и EOF имеют значение True.

Можно использовать методы MoveFirst, MoveLast, MoveNext и MovePrevious . Метод Move ; и свойства AbsolutePosition, AbsolutePage и Filter для изменения положения текущей записи при условии, что поставщик поддерживает соответствующие функциональные возможности. Объекты Recordset , доступные только для прямого доступа, поддерживают только метод MoveNext . При использовании методов Move для посещения каждой записи (или перечисления набора записей) можно использовать свойства BOF и EOF , чтобы определить, перешли ли вы за начало или конец набора записей.

Объекты Recordset могут поддерживать два типа обновления: немедленное и пакетное. При немедленном обновлении все изменения данных сразу же записываются в базовый источник данных после вызова метода Update . Вы также можете передать массивы значений в качестве параметров с помощью методов AddNew и Update и одновременно обновить несколько полей в записи.

Если поставщик поддерживает пакетное обновление, поставщик может кэшировать изменения в нескольких записях, а затем передавать их в одном вызове в базу данных с помощью метода UpdateBatch . Это относится к изменениям, внесенным с помощью методов AddNew, Update и Delete . После вызова метода UpdateBatch можно использовать свойство Status , чтобы проверить наличие конфликтов данных, чтобы устранить их.

Чтобы выполнить запрос без использования объекта Command , передайте строку запроса в метод Open объекта Recordset . Однако объект Command необходим, если требуется сохранить текст команды и повторно выполнить его или использовать параметры запроса.

Свойство Mode управляет разрешениями доступа.

Коллекция Fields является членом объекта Recordset по умолчанию. В результате следующие два оператора кода эквивалентны.

Источник

A Recordset is the one which sores the data retrived from a SQL query.

It represents the entire set of records from a base table or the results of an executed command.

Recordset are almost always used along with ADO.

A recordset object consists of «Records» also known as Rows and «Fields» or Columns.

There are various methods and properties of Recordset object, the availability of which are dependent on

the provider used.

Some of the most common methods and properties of Recordset object is discussed below.

Update method

This method saves any changes or modifications made to the current row of the recordset.

without Update method, the recordset will not be updated.

Syntax:

.Fields.Update

AddNew Method

This method is used to create and initialize new record in a recordset.

The records added through AddNew method acts as the current record of the recordset.

The AddNew method should be used along with the Update method.

Syntax

.AddNew FieldLists,Values

Close method

The Close method is of general type and can be used along with Connection,a record or recordset.

This method is used to close any active recordset objects.

Note that, closing a recordset does not delete it and is always accessible again when opened.

Syntax

.Close

EOF and BOF

EOF and BOF properties are used while looping through a recordset.

EOF indicates that the current record position is after the last record in a recordset.

While BOF indicates that the current recod position is before the first record in a recordset.

These properties are used to determine if a recordset object contains records or its limit is reached.

The EOF return TRUE if the current record position is after the last record.

Similarly, The BOF returns TRUE if the current record position is before the first record.

RecordCount Property

As the name indicates, this property returns the number of records in a recordset.

This property returns a long datatype.

The RecordCount property can be used in a recordset that is open.

Using this property in a closed Recordset object results in error.

You can find similar Excel Questions and Answer hereunder

1) How can i filter multiple columns simultaneously in Excel

2) How can I have text autocomplete by typing in a short code for the text?

3) Here some explanations about xml and how to use xml in VBA

4) Formula converts date to quarter and year in Excel

5) What is activeX data object in Excel. How to use it? Here the basic explanations

6) I have data arranged in rows of information. Is there any way I can enter new data through a form instead of entering it directly in SpreadSheet?

7) Here some explanations about the XML DOM node in VBA, DOM stands for Document Object Model

8) How can I enter information in multiple cells simultaneously?

9) How to use goal seek in Excel. Some good introduction to goal seeking function

10) Highlight row of selected cell in Excel

Table of Contents

Definitive Guide To ADO in Excel and VBA

There are several methods to work with external data and files in Excel. ADO (ActiveX Data Objects) is one of the best and most frequently used tools to work with external data and files. In Excel, we can use the combination of ADO with VBA (Visual Basic for Applications) to work with external data sets in memory. ADO always comes in handy when we need to perform complex, multi-layered procedures and checks on external datasets.

What is ActiveX Data Objects (ADO)?

ADO in Excel and VBA is a tool in that helps developers to write VBA code to access data without knowing how the database is implemented; developers should be aware of the database connectivity only. Being a developer, you don’t need to know the SQL to access a database when using ADO, although you can run SQL commands directly using ADO. So, in short, ADO helps developers accomplish two major tasks:

  • Connect to a data source
  • Specify the datasets with which to work

Using the ADODB connection, we connect our VBA application with the databases e.g., SQL, MS Access, Microsoft List, Excel workbook, etc.,

Understanding the fundamental syntax of ADO (Connection String and Recordset)

While dealing with external data and files, we must connect the data source before doing anything. To establish the connection, we must provide VBA a few pieces of information. The required information will be provided to VBA in the form of the connection string.

What is a connection string?

A connection string is nothing but a text string that contains a series of variables (also called arguments), which VBA uses to identify the data source and open the connection for further use.

Let’s understand the connection string and its arguments that point to an MS Access database and MS Excel Workbook. You can find several other connection strings at ConnectionStrings.com – Forgot that connection string? Get it here!

Connection Sting – MS Access database 

“Provider=Microsoft.ACE.OLEDB.12.0; ” & _
“Data Source= C:MyDatabase.accdb;” & _
“User ID= Administrator;” & _
“Password= AdminPassword”

Connection Sting – MS Excel workbook

“Provider=Microsoft.ACE.OLEDB.12.0; ” & _
“Data Source= C:MyExcelWorkbook.xlsx;” & _
“Extended Properties=Excel 12.0”

ADO connection string can have multiple arguments basis the data source type. Let’s understand the arguments which commonly used i.e., Provider, Data Source, Extended Properties, User ID, and Password (the same have been used in the previous example for MS Access and Excel).

Live Project – Data Entry Application in Excel and VBA using ADO
Data Entry Application in Excel and Access

Provider: With the help of Provider argument in the connection string, VBA identifies the type of data source we are going to work with. Suppose we are going to work with MS Access or MS Excel datasets, then the Provider syntax will be:

Provider=Microsoft.ACE.OLEDB.12.0

Data Source: This argument helps VBA to find the source of database or workbook that contains the data needed. For this parameter, we need to pass the full path of the database or workbook. For example:

Data Source=C:MydirectoryMyDatabaseName.accdb

Extended Properties: Extended Properties is required when we connect to an Excel Workbook. With the help of this argument, VBA identifies that data source is something else than a database. You can use this argument below:

Extended Properties=Excel 12.0

User ID: The User ID argument is optional and only used if the data source is protected with a user id and password. For example:

User Id = Admin

Password: This argument is optional and only need if the password is required to connect to the data source. For example:

Password = MyPassword

Note: You can skip User ID and Password arguments if the data source is not protected.

What is a Recordset?

A Recordset object is a group of records that can either come from a data source or as the output of a query to the table. The Recordset provides several methods and properties to examine the data that exists within the data source.

In addition to building a connection to the data source, we need to define the dataset (Recordset) with which we need to work. We can define the Recordset to open an existing table or query using the 4 common arguments: Source, ConnectString, CursorType, and LockType.

Recordset.Open Source, ConnectString, CursorType, LockType

Let’s understand all these 4 parameters.

Source in Recordset

The source data is typically a table, a SQL statement, or a query that retrieves records from the data source. Please see the below example of Source in different scenarios.

Providing MS Access table name ‘Product’ to Source

Recordset.Open “Product”

SQL statement to Source. In below code, MySQL is a variable holding SQL statement.

MySQL=”Select * from [Product] where Region=”North’”
Recordset.Open MySQL

ConnectString in Recordset

ConnectString is the argument that we have already discussed while understanding the ConnectionString. We just need to pass the ConnectionString here so that Recordset can identify the data source.

So, suppose we are going to connect with MS Access table ‘Product’ in Recordset then the code will be like:

Recordset.Open Product, ConnectionString

CursorType in Recordset

A cursor is a mechanism that enables the Recordset to move over the records in a database. It allows developers to retrieve each row at a time and manipulate its data. In simple language, a cursor is nothing more than a point to a row on which you are performing the data manipulation work.

The CursorType that are commonly used in Recordset code:

  1. adOpenForwardOnly: This is the default cursor type available in Recordset. If we don’t pass any CursorType in the code, then Recordset will automatically consider adOpenForwardOnly. This cursor is very efficient and allows us to move through the Recordset from beginning to end (one way only). This cursor is ideal for reporting purposes where we need to extract the data. This cursor does not allow to perform any changes to data.
  2. adOpenDynamic: When we need to loop through the data, moving up and down in the datasets, and want to identify any edits made to the dataset then adOpenDynamic can be used in Recordset. As it performs almost all the activities required in database operation, this cursor takes a lot of memory and resources of the system and should be used only when needed.
  3. adOpenStatic: This CursorType is ideal for quick return as it uses a static copy of data from the database. This is different from adOpenForwardOnly CursorType as it allows the developer to navigate the returned records. In addition to these, this CursorType allows data to be updateable by setting the LockType except adLockReadOnly (we will see LockType in upcoming part of this blog).

LockType: A LockType is a mechanism that helps developer to apply restrictions on a table or datasets to avoid unauthorized access or changes to the Recordset. We usually use two LockType in ADO:

  • adLockReadOnly: This is the default LockType in Recordset which indicates that there is no need to edit the data returned. If we don’t provide the LockType to Recordset then VBA considers this internally.
  • adLockOptimistic: This LockType is ideal when we need to edit the data returned to Recordset. We can use this if we want to perform Add, Update and Delete method in the database.

Referencing the ADO object library in VBA

Now, we have strong fundamentals of ADO and the codes/arguments. Let’s create our own ADO procedures to perform some basic operations. It will help us get more clarity and understanding of ADO in real projects.

To use the ADO in the Excel project, we need to add the reference of the ADO object library in the Visual Basic Application (VBA) window. Once we add the reference of ADO in the Excel project, Excel will start understanding the objects, properties, and methods of ADO.

Note: we can use ADO library without giving the reference of ADO in Excel with Late Binding technique, but it will increase the complexity of code and you will not be able to get the help while writing the code. So, we would recommend you start using the Early Binding i.e., giving the reference of ADO and then writing the code. Once you have expertise in the code then you can move to Late Binding technique.

To start adding the reference of ADO, just open the MS Excel application and create a new workbook and save the file with a Macro enabled extension e.g., .xlsm. Open the Visual Basic Editor window using the Shortcut key ALT + F11.

image 11

Saving Excel file with macro enabled extension

Once Visual Basic Editor window will appear on screen then click on Tools (available in the application menu) -> References….

image 12

Tool menu to open Reference Dialog Box

Once you click on References.. then it will open the References dialog box as shown in the picture below. In the available references list, just scroll down until you find the latest version of the Microsoft ActiveX Data Objects Library. Just tick the Checkbox and click on the OK button available in the dialog box to add the ADO reference to the current Excel file.

image 13

Reference Dialog Box in VBA to Select ADO

Note: you can see several versions of the ADO library in Reference dialog box. We would recommend you select the latest version from the list or if you are developing a project for your client then check the version of MS Excel and available ADO on client system and then go with that library to make your code compatible.

After clicking on OK button, we can open the Reference dialog box again to ensure that whether the ADO reference is selected or not. If that is selected, then it will start appearing on top of the list as check marked (as you can see in above image).

VBA code to Use ADO and get data from MS Access database

Writing the code to get the data from Customer table of MS Access database.

Sub GetCustomerData ()
Dim MyConnect as String
Dim MyRecordset as ADODB.Recordset
MyConnect= “Provider=Micorosft.ACE.OLEDB.12.0;” & _
“Data Source= D:TheDataLabsSales.accdb”
Set MyRecordset= New ADODB.Recordset
MyRecordset.Open “Customer”, MyConnect, adOpenStatic, adLockReadOnly
ThisWorkbook.Sheets(“Customer”).Range(“A2”).CopyFromRecordset MyRecorset
With ActiveSheet.Range (“A1:C1”)
.value = Array (“Name”, “Gender”, “Address”)
.EntireColumn.AutoFit
End With
End Sub

Now we are done with putting all the code together in a procedure to get the data from Customer table and provide the output in MS Excel worksheet “Customer”.

Understand VBA Codes line by line

For better clarity, let’s take a moment to understand the VBA code.

Sub GetCustomerData ()

With the help of this line, we are declaring a procedure named ‘GetCustomerData’.

Dim MyConnect as String

Declaring a string variable to hold the Connection sting so that VBA can identify the data source.

Dim MyRecordset as ADODB.Recordset

Declaring a Recordset object variable to hold the data that will be returned by the procedure.

MyConnect= “Provider=Micorosft.ACE.OLEDB.12.0; Data Source= D:TheDataLabsSales.accdb”

Here, we are defining the connection string for the ADO procedure. As we are connecting the ‘Sales’ MS database to get the data from the Customer table hence, we are passing the Provider parameter as Micorosft.ACE.OLEDB.12.0 and Source as D:TheDataLabsSales.accdb. The same has been already discussed in the Connection String section of the post.

Set MyRecordset= New ADODB.Recordset

With the help of the line of code, we are setting the reference of ADODB Recordset to MyRecordset object variable.

MyRecordset.Open “Customer”, MyConnect, adOpenStatic, adLockReadOnly

This line of code helps us in opening the Recordset to return static and read-only data.

ThisWorkbook.Sheets(“Customer”).Range(“A2”).CopyFromRecordset MyRecorset

Here, we are using Excel’s CopyFromRecordset method to get the data from the Recordset and provide the output in the range starting from the “A2” to the spreadsheet named ‘Customer’.

With ActiveSheet.Range (“A1:C1”) …. End With

These lines of Code help us in getting the column header and putting the header name in active sheet range A1 to C1. We need these lines of code because the CopyFromRecordset method does not return column headers or field names.

Live Project in Excel

Using ADO with Microsoft Visual Basic, we have developed the Data Entry Application Project in MS Excel and MS Access to transfer the data. Refer the below link.
Data Entry Application in Excel and Access

Interested in developing Data Entry Form without Using ADO
Easy-To-Follow: Create a Fully Automated Data Entry Userform in Excel and VBA in 5 Easy Steps
How to Create a Multi-User Data Entry Form in Excel (Step-by-step Guide)
Advance Data Entry Form

Read more topics

If you have any question on ‘Definitive Guide To ADO in Excel and VBA’ then please leave your comment in comment section. Thanks!

Чтобы подключиться к файлу Excel, нам потребовалось: создать именованный диапазон в книге Excel;

создать источник данных ODBC с именем ExcelVolumes;

написать три строки кода, начиная с создания объекта Connection до вызова его метода Open.

9.5.1. Открытие Recordset

Обычно следующий после установки соединения этап — это создание объекта Recordset и работа с ним.

Что такое объект Recordset? Само слово Recordset расшифровывается как Set of Records, т. е. набор записей. Проще всего представить его как таблицу (аналогичную таблицам в Excel), которая находится в оперативной памяти компьютера. Однако у Recordset есть принципиальные отличия от таблиц

Excel:

Excel не следит за «строгостью» таблиц. На предприятиях часто можно встретить таблицы, в середину которых вставлены, например, промежуточные итоги по группам или заметки. Recordset — это «строгая» таблица. В ней четко определены столбцы и строки и разрывов она не допускает (хотя какие-то значения на пересечении строк и столбцов вполне могут быть пустыми);

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

Recordset обычно создается на основе данных, полученных с источника (но может быть создан и заполнен вручную), в которых предусмотрены столбцы (Fields) и строки (Rows). Создание объекта Recordset и заполнение его данными с источника в самом простом варианте выглядит так (подразумевается, что мы открыли при помощи объекта cn соединение с учебной базой данных

Northwind на SQL Server):

Dim rs As New ADODB.Recordset rs.Open «customers», cn

Убедиться, что Recordset действительно создан и существует, можно, например, при помощи строки:

MsgBox rs.GetString

Работа с базами данных и применение объектной модели ADO

175

При открытии Recordset вполне могут возникнуть ошибки, поэтому рекомендуется использовать обработчик ошибок. Специальной коллекции Errors в Recordset не предусмотрено, а значит, придется обойтись стандартным объектом Err.

В нашем примере мы открыли таблицу Customers целиком. Однако это не единственный (и не лучший) способ извлечения данных с источника. Для метода Open() рекомендуется использовать запрос на языке SQL. Например, в нашем случае можно было бы использовать такой код:

rs.Open «select * from dbo.customers», cn

Запрос использовать лучше, потому что:

есть возможность указать фильтр Where (условие обязательно заключать в одинарные кавычки) и скачать в Recordset не все записи, а только удовлетворяющие вашему условию;

есть возможность точно так же ограничить число возвращаемых столбцов — снова сокращение объема передаваемых данных и уменьшение расхода памяти;

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

Очень часто в реальных приложениях текст запроса «склеивается» из кусочков, которые поступают из разных мест. Например, пользователь выбрал в раскрывающемся списке имя заказчика, и для события Change этого списка тут же сработала процедура, которая выполнила запрос на SQL Server, получив данные только для этого заказчика, и присвоила полученные значения другим элементам управления. В нашем случае соответствующая строка кода может выглядеть так:

rs.Open «select * from dbo.customers Where CompanyName = » & «‘» _ & ComboBox1.Value & «‘» , cn

Набор символов «‘» — это одинарная кавычка внутри двух двойных. Такая конструкция нужна, чтобы текст запроса мог выглядеть, например, так:

select * from dbo.customers Where CompanyName = ‘Alfreds Futterkiste’

Причина проста — в языке SQL строковые значения нужно заключать в одинарные кавычки.

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

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

И еще один практический момент. Конечно, для работы с базами данных знать язык запросов SQL очень полезно. Литературы по нему очень много, и его вполне реально освоить за несколько дней. Однако, если вы — обычный пользователь и не имеете об языке SQL никакого представления, ничего страшного. Просто открывайте таблицы целиком без всяких запросов, а все остальное можно будет сделать средствами VBA.

9.5.2. Настройки курсора

и другие параметры открытия Recordset

При открытии объекта Recordset можно определить еще несколько важных его свойств (их можно определить как напрямую перед открытием, так и передать как дополнительные параметры методу Open()).

Первое свойство — CursorType, тип курсора. Это свойство определяется только перед открытием Recordset (после открытия оно доступно только для чтения). Курсор можно представить себе как указатель на записи в Recordset. В зависимости от типа курсора мы определяем возможности работы с Recordset и производительность выполняемых операций (чем больше возможностей, тем меньше производительность, и наоборот). Можно задавать следующие значения:

adOpenForwardOnly — это значение используется по умолчанию. Оно

оптимизировано для достижения максимальной производительности (его возможности будут минимальными). Курсор может двигаться только вперед, а изменения, вносимые другими пользователями, видны не будут;

adOpenStatic — то же самое, что и предыдущее значение, за исключе-

нием того, что курсор может двигаться во всех направлениях;

adOpenKeyset — позволяет двигаться курсору в любом направлении,

видны только изменения существующих записей другими пользователями (удаление старых записей и добавление новых не видны);

adOpenDynamic — обеспечивает максимальные возможности: позволяет

двигаться в любых направлениях, видны любые изменения в записях, производимые другими пользователями. К сожалению, провайдер Microsoft.Jet.OLEDB.4.0 этот тип курсора не поддерживает, поэтому с Access и Excel его использовать не получится.

Свойство Recordset.RecordCount нормально функционирует только для курсоров типа adOpenStatic и adOpenKeyset. Для курсоров типа

Работа с базами данных и применение объектной модели ADO

177

adOpenForwardOnly и adOpenDynamic оно возвращает 1, поскольку драйвер подключения не может определить количество записей.

Второе важное свойство — CursorLocation. Оно определяет, где будет создан курсор — на сервере или на клиенте. По умолчанию используется значение adUseServer (создавать на сервере). Второе значение — adUseClient (создавать на клиенте). В целом, практически во всех ситуациях удобнее и производительнее использовать серверные курсоры, за одним исключением — в реализации серверных курсоров на разных источниках данных много отличий, поэтому если вы планируете работать с разными источниками, имеет смысл подумать о клиентских курсорах.

Третье важное свойство — LockType. Это свойство определяет тип блокировок, которые будут наложены на записи на источнике, помещенные в Recordset. Можно использовать следующие значения:

adLockReadOnly — записи в Recordset будут доступны только для чте-

ния, вы не сможете их изменять. Это значение используется по умолчанию;

adLockPessimistic — наиболее надежный, с точки зрения целостности

данных, вид блокировки. Вы можете изменять записи в Recordset, но при начале изменения записи она блокируется на источнике таким образом, что другие пользователи не смогут обратиться к ней ни на чтение, ни на запись, пока вы не вызовете методы Update() или

CancelUpdate();

adLockOptimistic — это значение позволяет выиграть в производитель-

ности за счет проигрыша в надежности обеспечения целостности данных. Запись на источнике блокируется только на время выполнения метода Update(). Остальные пользователи могут одновременно с вами читать и изменять данные на источнике;

adLockBatchOptimistic — то же самое, что и adLockOptimistic, но вме-

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

Первый параметр метода Open() в наших примерах был как именем таблицы, так и командой SQL (могут использоваться и другие варианты). Поскольку драйвер OLE DB не знает, чем может быть передаваемый текст, он взаимодействует с сервером баз данных, чтобы определить это. На практике такое выяснение может сильно тормозить работу приложения, поэтому имеет смысл перед открытием Recordset явно указать тип передаваемых параметров. Это делается при помощи параметра Options, который передается этому методу.

Содержание

  • 1 A Recordset That Does Not Support the RecordCount Property
  • 2 A Recordset That Supports the RecordCount Property
  • 3 Assigning Recordsets Dynamically to a form
  • 4 Build a string text from result set
  • 5 Creating a Custom Recordset
  • 6 Creating a Disconnected Recordset
  • 7 Dynamic Recordset
  • 8 Filling a Combo Box with a Disconnected Recordset
  • 9 Looping Through a Recordset
  • 10 Move cursor in result set
  • 11 Refreshing Recordset Data
  • 12 Retrieve data from Recordset by table column name
  • 13 Row order in Dynamic Recordset
  • 14 Set Index and seek the recordset
  • 15 Set recordset to form
  • 16 Snapshot Recordset
  • 17 The Sort Property of the Recordset Object
  • 18 The Supports Method of the Recordset Object
  • 19 Using the AbsolutePosition Property
  • 20 Using the Bookmark Property
  • 21 Using the EOF Property to Determine the Bounds of a Recordset
  • 22 Whether Records Are Returned in a Recordset

A Recordset That Does Not Support the RecordCount Property

   <source lang="vb">

Sub CountRecordsBad()

   Dim rst As ADODB.Recordset
   Set rst = New ADODB.Recordset
   rst.ActiveConnection = CurrentProject.Connection
   rst.Open "Select * from Employees"
   Debug.Print rst.RecordCount  "Prints -1
   rst.Close
   Set rst = Nothing

End Sub

</source>
   
  

A Recordset That Supports the RecordCount Property

   <source lang="vb">

Sub CountRecordsGood()

   Dim rst As ADODB.Recordset
   Set rst = New ADODB.Recordset
   rst.ActiveConnection = CurrentProject.Connection
   rst.CursorType = adOpenStatic
   rst.Open "Select * from Employees"
   Debug.Print rst.RecordCount  "Prints Record count
   rst.Close
   Set rst = Nothing

End Sub

</source>
   
  

Assigning Recordsets Dynamically to a form

   <source lang="vb">

Sub runFormNY()

   Dim con As ADODB.Connection
   Dim myRecordset As Recordset
   Dim strFrmNm As String
   
   Set myRecordset = New ADODB.Recordset
   myRecordset.CursorType = adOpenKeyset
   myRecordset.LockType = adLockOptimistic 
   Set con = New ADODB.Connection
   con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:mydb.mdb;"
      myRecordset.Open "SELECT * FROM Employees", con
      strFrmNm = "frmCustomer"
   DoCmd.OpenForm strFrmNm
   Set Application.Forms(strFrmNm).Recordset = myRecordset
   
   myRecordset.Close
   con.Close
   Set myRecordset = Nothing
   Set con = Nothing

End Sub

</source>
   
  

Build a string text from result set

   <source lang="vb">

Sub MyFirstConnection4()

   Dim myConnection As ADODB.Connection
   Dim myRecordset As ADODB.Recordset
   Dim strSQL As String
   Dim strOutput As String
  
   strSQL = "SELECT FirstName, LastName FROM Employees"
   
   Set myConnection = CurrentProject.Connection
   
   Set myRecordset = New ADODB.Recordset
   myRecordset.Open strSQL, myConnection
   
   Do Until myRecordset.EOF
      strOutput = strOutput + myRecordset.Fields("FirstName") & " " & _
                              myRecordset.Fields("LastName") & vbCrLf
      myRecordset.MoveNext
   Loop
   myRecordset.Close
   msgBox strOutput
   myConnection.Close
   Set myConnection = Nothing
   Set myRecordset = Nothing

End Sub

</source>
   
  

Creating a Custom Recordset

   <source lang="vb">

Sub Custom_Recordset()

   Dim myRecordset As ADODB.Recordset
   Dim strFile As String
   Dim strFolder As String
   strFolder = "C:"
   strFile = Dir(strPath & "*.*")
   Set myRecordset = New ADODB.Recordset
   With myRecordset
      Set .ActiveConnection = Nothing
          .CursorLocation = adUseClient
          With .Fields
                    .Append "Name", adVarChar, 255
                    .Append "Size", adDouble
                    .Append "Modified", adDBTimeStamp
          End With
           .Open
             " Add a new record to the recordset
             .AddNew Array("Name", "Size", "Modified"), _
              Array("fileName.txt", 100, #9/9/1999#)
           .MoveFirst
            " Print the contents of the recordset to the Immediate window
                Do Until .EOF
                     Debug.Print !Name & vbTab & !Size & vbTab & !Modified
                    .MoveNext
                Loop
                .Close
        End With
    Set myRecordset = Nothing

End Sub

</source>
   
  

Creating a Disconnected Recordset

   <source lang="vb">

Sub Rst_Disconnected()

   Dim conn As ADODB.Connection
   Dim myRecordset As ADODB.Recordset
   Dim strConn As String
   Dim strSQL As String
   Dim strRst As String
   strSQL = "Select * From Orders where CustomerID = "VINET""
   strConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
   strConn = strConn & "Data Source = " & CurrentProject.Path & "mydb.mdb"
   Set conn = New ADODB.Connection
   conn.ConnectionString = strConn
   conn.Open
   Set myRecordset = New ADODB.Recordset
   Set myRecordset.ActiveConnection = conn
   " retrieve the data
   myRecordset.CursorLocation = adUseClient
   myRecordset.LockType = adLockBatchOptimistic
   myRecordset.CursorType = adOpenStatic
   myRecordset.Open strSQL, , , , adCmdText
   Set myRecordset.ActiveConnection = Nothing
   myRecordset.MoveFirst
   Debug.Print myRecordset.Fields(0) & " was " & myRecordset.Fields(1) & " before."
   myRecordset.Fields("CustomerID").Value = "OCEAN"
   myRecordset.Update
   strRst = myRecordset.GetString(adClipString, , ",")
   Debug.Print strRst

End Sub

</source>
   
  

Dynamic Recordset

   <source lang="vb">

Sub exaRecordsetPosition()

   Dim db As Database
   Dim rsDyna As Recordset
   Set db = CurrentDb
   Set rsDyna = db.OpenRecordset("Books", dbOpenDynaset)
   rsDyna.MoveFirst
   Do While Not rsDyna.EOF
       Debug.Print rsDyna!PubID & " / " & rsDyna!Title
       Debug.Print rsDyna.AbsolutePosition
       Debug.Print Format$(rsDyna.PercentPosition
       rsDyna.MoveNext
   Loop
   rsDyna.Close

End Sub

</source>
   
  

Filling a Combo Box with a Disconnected Recordset

   <source lang="vb">

Private Sub Form_Load()

  Dim myRecordset As ADODB.Recordset 
  Dim strRowSource As String 
  Dim strName As String 
  strName = CurrentProject.Path & "Companies.rst" 
  Set myRecordset = New ADODB.Recordset 
     With myRecordset 
        .CursorLocation = adUseClient 
        .Open strName, , , ,  adCmdFile 
        Do Until .EOF 
           strRowSource = strRowSource & myRecordset!CompanyName & ";" 
           .MoveNext 
        Loop 
        With Me.cboCompany 
           .RowSourceType = "Value List" 
           .RowSource = strRowSource 
        End With 
        .Close 
     End With 
  Set myRecordset = Nothing 

End Sub

</source>
   
  

Looping Through a Recordset

   <source lang="vb">

Sub LoopThroughRecordset(rst As ADODB.Recordset, rg As Range)

   Dim nColumnOffset As Integer 
   Dim fld As ADODB.Field 
   With rst 
       Do Until .EOF 
           nColumnOffset = 0 
           For Each fld In .Fields 
               rg.Offset(0, nColumnOffset).Value = fld.Value 
               nColumnOffset = nColumnOffset + 1 
           Next 
           Set rg = rg.Offset(1, 0) 
           .MoveNext 
       Loop 
   End With 
   Set fld = Nothing 

End Sub

</source>
   
  

Move cursor in result set

   <source lang="vb">

Sub MyFirstConnection3()

   Dim myConnection As ADODB.Connection
   Dim myRecordset As ADODB.Recordset
   Dim strSQL As String
   
   strSQL = "SELECT FirstName, LastName FROM Employees"
   Set myConnection = CurrentProject.Connection
   
   Set myRecordset = New ADODB.Recordset
   myRecordset.Open strSQL, myConnection
   
   Do Until myRecordset.EOF
      Debug.Print myRecordset.Fields("FirstName") & " " & _
                  myRecordset.Fields("LastName")
      myRecordset.MoveNext
   Loop
   myRecordset.Close
   myConnection.Close
   Set myConnection = Nothing
   Set myRecordset = Nothing

End Sub

</source>
   
  

Refreshing Recordset Data

   <source lang="vb">

Sub PersistRecordset()

   Dim strFileName As String
   strFileName = "c:test.txt"
   Dim rst As ADODB.Recordset
   Set rst = New ADODB.Recordset
   rst.ActiveConnection = CurrentProject.Connection
   rst.CursorType = adOpenStatic
   rst.LockType = adLockOptimistic
   rst.Open Source:="Select * from Employees ", Options:=adCmdText
   On Error Resume Next
   Kill strFileName
   "Save the recordset
   rst.Save strFileName, adPersistADTG
   rst.Close
   Set rst = Nothing

End Sub

</source>
   
  

Retrieve data from Recordset by table column name

   <source lang="vb">

Sub MyFirstConnection()

   Dim myConnection As ADODB.Connection
   Dim myRecordset As ADODB.Recordset
   Set myConnection = CurrentProject.Connection
   
   Set myRecordset = New ADODB.Recordset
   myRecordset.Open "select * from employees", myConnection
   
   Do Until myRecordset.EOF
      Debug.Print myRecordset.Fields("FirstName"), _
                  myRecordset.Fields("LastName")
      myRecordset.MoveNext
   Loop
   myRecordset.Close
   myConnection.Close
   Set myConnection = Nothing
   Set myRecordset = Nothing

End Sub

</source>
   
  

Row order in Dynamic Recordset

   <source lang="vb">

Sub exaRecordsetMove()

   Dim db As Database
   Dim rsTable As Recordset
   Dim rsDyna As Recordset
   
   Set db = CurrentDb
   
   Set rsTable = db.OpenRecordset("Books")
   Debug.Print "Books indexed by PubID/Title:"
   
   rsTable.Index = "PubTitle"
   rsTable.MoveFirst
   Do While Not rsTable.EOF
       Debug.Print rsTable!PubID & " / " & rsTable!Title
       rsTable.MoveNext
   Loop
   
   Debug.Print "Dynaset-type recordset order:"
   Set rsDyna = db.OpenRecordset("Books", dbOpenDynaset)
   rsDyna.MoveFirst
   Do While Not rsDyna.EOF
       Debug.Print rsDyna!PubID & " / " & rsDyna!Title
       rsDyna.MoveNext
   Loop
   
   rsTable.Close
   rsDyna.Close

End Sub

</source>
   
  

Set Index and seek the recordset

   <source lang="vb">

Sub exaRecordsetSeek()

   Dim db As Database
   Dim rsTable As Recordset
   
   Set db = CurrentDb
   
   Set rsTable = db.OpenRecordset("Books")
   rsTable.Index = "Title"
   rsTable.Seek ">=", "On"
   If Not rsTable.NoMatch Then
       Debug.Print rsTable!Title
   Else
       Debug.Print "No title beginning with word "On"."
   End If
   
   rsTable.Close

End Sub

</source>
   
  

Set recordset to form

   <source lang="vb">

Private Sub Form_Open(Cancel As Integer)

   Dim con As ADODB.Connection
   Dim myRecordset As ADODB.Recordset
   Dim strFrmNm As String
   
   Set myRecordset = New ADODB.Recordset
   myRecordset.CursorType = adOpenKeyset
   myRecordset.LockType = adLockOptimistic
   Set con = New ADODB.Connection
   con.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
      "Data Source=C:store.mdb;"
      
   myRecordset.Open "SELECT * FROM tblCustomer", con
   Set Me.Recordset = myRecordset
   
   myRecordset.Close
   con.Close
   Set myRecordset = Nothing
   Set con = Nothing

End Sub

</source>
   
  

Snapshot Recordset

   <source lang="vb">

Sub exaRecordsets()

   Dim db As Database
   Dim rsTable As Recordset
   Dim rsDyna As Recordset
   Dim rsSnap As Recordset
   Set db = CurrentDb
   Set rsTable = db.OpenRecordset("Employees")
   Debug.Print "TableCount: " & rsTable.RecordCount
   Set rsDyna = db.OpenRecordset("Employees", dbOpenDynaset)
   Debug.Print "DynaCount: " & rsDyna.RecordCount
   rsDyna.MoveLast
   Debug.Print "DynaCount: " & rsDyna.RecordCount
   
   Set rsSnap = db.OpenRecordset("Employees", dbOpenSnapshot)
   Debug.Print "SnapCount: " & rsSnap.RecordCount
   rsSnap.MoveLast
   Debug.Print "SnapCount: " & rsSnap.RecordCount
   
   rsTable.Close
   rsDyna.Close
   rsSnap.Close
   

End Sub

</source>
   
  

The Sort Property of the Recordset Object

   <source lang="vb">

Sub SortRecordset()

   Dim intCounter As Integer
   Dim rst As ADODB.Recordset
   Set rst = New ADODB.Recordset
   rst.ActiveConnection = CurrentProject.Connection
   rst.CursorLocation = adUseClient
   rst.Open "Select * from Employees"
   Debug.Print "NOT Sorted!!!"
   Do Until rst.EOF
       Debug.Print rst("EmployeeID")
       rst.MoveNext
   Loop
   Debug.Print "Now Sorted!!!"
   rst.Sort = "[EmployeeID]"
   Do Until rst.EOF
       Debug.Print rst("EmployeeID")
       rst.MoveNext
   Loop
   rst.Close
   Set rst = Nothing

End Sub

</source>
   
  

The Supports Method of the Recordset Object

   <source lang="vb">

Sub SupportsMethod()

   Dim rst As ADODB.Recordset
   Set rst = New ADODB.Recordset
   
   rst.ActiveConnection = CurrentProject.Connection
   rst.CursorType = adOpenStatic
   rst.LockType = adLockOptimistic
   rst.CursorLocation = adUseServer
   rst.Open Source:="Select * from Employees ", _
       Options:=adCmdText
   Debug.Print "Bookmark " & rst.Supports(adBookmark)
   Debug.Print "Update Batch " & rst.Supports(adUpdateBatch)
   Debug.Print "Move Previous " & rst.Supports(adMovePrevious)
   Debug.Print "Seek " & rst.Supports(adSeek)
   rst.Close
   Set rst = Nothing

End Sub

</source>
   
  

Using the AbsolutePosition Property

   <source lang="vb">

Sub FindPosition()

   Dim strSQL As String
   Dim rst As ADODB.Recordset
   Set rst = New ADODB.Recordset
   rst.ActiveConnection = CurrentProject.Connection
   rst.CursorType = adOpenStatic
   rst.Open "Select * from Products"
   strSQL = "[ProductID] = " & 1
   rst.Find strSQL
   "If record is found, print its position
   If rst.EOF Then
       msgBox lngValue & " Not Found"
   Else
       Debug.Print rst.AbsolutePosition
   End If
   rst.Close
   Set rst = Nothing

End Sub

</source>
   
  

Using the Bookmark Property

   <source lang="vb">

Sub UseBookmark()

   Dim strSQL As String
   Dim vntPosition As Variant
   Dim rst As ADODB.Recordset
   Set rst = New ADODB.Recordset
   rst.ActiveConnection = CurrentProject.Connection
   rst.CursorType = adOpenStatic
   rst.Open "Select * from Products"
   vntPosition = rst.Bookmark
   Do Until rst.EOF
       Debug.Print rst("ProductID")
       rst.MoveNext
   Loop
   rst.Bookmark = vntPosition
   Debug.Print rst("ProductID")
   rst.Close
   Set rst = Nothing

End Sub

</source>
   
  

Using the EOF Property to Determine the Bounds of a Recordset

   <source lang="vb">

Sub DetermineLimits()

   Dim rst As ADODB.Recordset
   Set rst = New ADODB.Recordset
   rst.ActiveConnection = CurrentProject.Connection
   rst.CursorType = adOpenStatic
   rst.Open "Select * from Employees"
   Do Until rst.EOF
       Debug.Print rst("EmployeeID")
       rst.MoveNext
   Loop
   rst.Close

End Sub

</source>
   
  

Whether Records Are Returned in a Recordset

   <source lang="vb">

Sub CheckARecordset()

   Dim rst As ADODB.Recordset
   Set rst = New ADODB.Recordset
   rst.ActiveConnection = CurrentProject.Connection
   rst.CursorType = adOpenStatic
   rst.Open "Select * from Employees"
   If Not rst.RecordCount Then
     msgBox "Recordset Empty...Unable to Proceed"
   End If
   rst.Close
   Set rst = Nothing

End Sub

</source>

Понравилась статья? Поделить с друзьями:
  • What is spanish word for food
  • What is range object in excel vba
  • What is spanish word for english
  • What is range name in excel
  • What is sorting in excel