Solved

# excel vba - code understanding

Posted on 2011-05-07
267 Views
Hi,
Can any please explain the below code
specially rs.EOF()
.MoveFirst, Movenext - are they pointers?
it would good to get as much knowledge on this code as possible

Thanks
With rs
If rs.EOF() Then .MoveFirst
Do While Not .EOF()
If .Fields("FirstName") = Range("E1").Value Then
Range("C4").Value = .Fields("FirstName")
Range("D4").Value = .Fields("LastName")
Exit Do
End If

.MoveNext

Loop
End With

0
Question by:SameerMirza

LVL 81

Expert Comment

EOF is a property that indicates whether or not the record pointer is beyond the end of the recordset. MoveFirst and MoveNext are methods that move the record pointer to the first or next record in the recordset.

Fields is a collection of the fields in the recordset. Use it to access the fields in the current record.

Kevin
0

LVL 81

Accepted Solution

Here is some information on how to use an ADODB connection.

The following text and sample code illustrates how to:

-> open a database connection
-> use a stored procedure to perform a query
-> execute any SQL command against a database
-> open a recordset using a custom query
-> open a recordset using a table name
-> check for an empty recordset
-> read all records in a recordset
-> add a record to a recordset
-> delete a record from a recordset
-> copy a recordset with headers to a worksheet
-> close a recordset and database

This sample code, except for Open database method, can be used with any database such as Access, SQL Server, or Oracle. When using a database, most interaction happens via a recordset. Data is manipulated almost entirely using Recordset objects. Any number of Recordset objects can be created and used at the same time - each representing a different query or the same query. Different Recordset objects can access the same tables, queries, and fields without conflicting.

After opening a Recordset the Recordset can contain zero or more records. One record in the Recordset is always the current record except when the Recordset BOF or EOF property is true in which case no record is the current record. The current record is the record that is affected by any record-specific methods. To move amongst the records in a Recordset use the MoveNext, MovePrevious, MoveLast, and MoveFirst Recordset methods. A specific record can be made the current record by setting the AbsolutePosition property to the index number of the desired record. Fields in the current record are access as illustrated below.

Value = MyRecordset!Field1
MyRecordset!Field2 = Value + 1

When the current record is changed use the Update method to apply the changes to the database. Use the Add method to add a new record and the Delete method to delete the current record. The Add method can be used even if the query returns an empty recordset.

Caution about using the RecordCount method: The RecordCount for a serverside recordset may return a -1. This occurs with ActiveX Data Objects (ADO) version 2.0 or later when the CursorType is adOpenForwardonly or adOpenDynamic and when with ADO 1.5 only when the cursortype is adOpenForwardonly. To get around this problem use either adOpenKeyset or adOpenStatic as the CursorType for server side cursors or use a client side cursor. Client side cursors use only adOpenStatic for CursorTypes regardless of which CursorType is selected.

Before writing any ADODB code the data objects library "Microsoft ActiveX Data Objects x.x Library" must be referenced in the VBA project (Tools->References).

For additional information on the ADODB interface see the MSDN pages at:

Sample code:

Dim Column As Long

' Open database connection
'   http://msdn.microsoft.com/en-us/library/ms808201.aspx
' Additional help constructing connection strings can be found at http://www.connectionstrings.com/

' Query database using stored procedure (requires command object)
Set MyCommand.ActiveConnection = MyDatabase
MyCommand.CommandText = "qrySomeQuery" ' <- name of procedure
With MyCommand
.Parameters.Refresh
'   http://msdn.microsoft.com/en-us/library/ms808298.aspx
End With

' Open recordset using command object
'   http://msdn.microsoft.com/en-us/library/ms808656.aspx

' Build a custom query using command object
With MyCommand
Set .ActiveConnection = MyDatabase
.CommandText = "SELECT * From tblMyTable WHERE (tblMyTable.MyID = 1)"
End With

' Execute any SQL statement
MyDatabase.Execute "INSERT INTO TableName (Field1, Field2) VALUES ('" & Range("A1").Value & "','" & Range("A2").Value & "')"

' Open a recordset by specifying specific table (no query)

' Open a recordset by specifying query without using command object

' Test for no records
If MyRecordset.BOF And MyRecordset.EOF Then
MsgBox "No records in table"
End If

' Determine total records (see notes above about inconsistencies with the RecordCount method)
MsgBox "Total records: " & MyRecordset.RecordCount

' Look at all records in record set
While Not MyRecordset.EOF
MsgBox "Record number: " & MyRecordset.AbsolutePosition
MyRecordset.MoveNext
Wend

' Find a specific record given a field value
MyRecordset.MoveFirst
MyRecordset.Find "ID='ABC123'"
If Not MyRecordset.BOF And Not MyRecordset.EOF Then
MyRecordset!Field1 = "Match Found"
MyRecordset.Update
End If

' Copy the entire recordset to a worksheet (this technique does not copy field names)
Sheets("Sheet1").[A2].CopyFromRecordset MyRecordset

' Create headers and copy data
With Sheets("Sheet1")
For Column = 0 To MyRecordset.Fields.Count - 1
.Cells(1, Column + 1).Value = MyRecordset.Fields(Column).Name
Next
.Range(.Cells(1, 1), .Cells(1, MyRecordset.Fields.Count)).Font.Bold = True
.Cells(2, 1).CopyFromRecordset MyRecordset
End With

' Update current record
MyRecordset!Field1 = "Some data"
MyRecordset!Field2 = "Some more data"
MyRecordset.Update

' Move specific fields from current record to worksheet
With Sheets("Sheet1")
Cells(Row, "A") = MyRecordset!Field1
Cells(Row, "B") = MyRecordset!Field2
End With

' Add new record and set field values
MyRecordset!Field1 = "Some data"
MyRecordset.Update

' Update an existing record or add it if it does not exist
MyRecordset.MoveFirst
MyRecordset.Find "Field1='"& SourceSheet.Cells(Row, "A") & "'"
If MyRecordset.BOF Or MyRecordset.EOF Then
End If
MyRecordset!Field1 = SourceSheet.Cells(Row, "A")
MyRecordset!Field2 = SourceSheet.Cells(Row, "B")
MyRecordset.Update

' Delete current record
MyRecordset.Delete

' Close recordset
MyRecordset.Close

' Close database
MyDatabase.Close

Kevin
0

Author Comment

thanks Kevin - its very helpful
I am very new to VBA
I can code but I need to clear my logics a little
So just a quick one
We can say,
'declaration
Dim firstName as string
'initialization
Set firstName = 'test'

and some time we even see
firstName = 'test'

I believe both statements work but how important is it to use 'Set' and when we must?

Thanks and sorry if it dosnt make any sense at all :)
0

LVL 81

Expert Comment

Use the Set command when setting any object. When setting any non-object variable such as a string, long, double, date, etc., then don't use Set.

So this is incorrect:

Set firstName = "Test"

This is correct:

firstName = "Test"

Kevin
0

Author Closing Comment

thanks :)
0

LVL 17

Expert Comment

Here is a simple explanation of each part of the code

With rs

rs in this case will refer to the recordset.  Literally the list of records that have been return from the database (or other datastore)

If rs.EOF() Then .MoveFirst

rs.EOF - if the recordset is at the last record in the set then move to the first record in the recordset

Do While Not .EOF()

Do this as long as the record is not the last record (when it becomes the last record the loop will stop and everything in between here and the "Loop" word in the code is finished with

If .Fields("FirstName") = Range("E1").Value Then

If the recordset field "FirstName" is the same as the value in cell E1 then do the following

Range("C4").Value = .Fields("FirstName")

set cell C4 = the value in the recordset field "Firstname"

Range("D4").Value = .Fields("LastName")

set cell D4 = the value in the recordset field "LastName"

set cell E4 = the value in the recordset field "Address"

Exit Do

Exit Do means that it will close of the Do While loop.  The code here is basically looping through the recordset,  If .Fields("FirstName") = Range("E1").Value is true then it will perform the set cell stuff explained above and exit out of the loop as is written to only run once the If statement is true.

End If

closes If statement

.MoveNext

moves to the next record in the recordset

Loop

Go back through the code from the Do While.... part (unless we have hit the Exit Do or we have reached the end of the recordset - ie looped through all the records)

End With

Ends using rs.  The With RS command is just a more effecient way of using objects, so instead of having to type rs.movenext, you just type .movenext.  The code already knows that anything begining .keyword is associated to rs so it runs faster (there is abit more to this, but that is the basics)

Hope that makes it a bit clearer
0

Author Comment

thanks alot wobbled
Unfortunatly I have already alocated the points but thanks
0

LVL 17

Expert Comment

Don't worry about - hope it helps you get started in VBA :)
0

## Featured Post

Drop Down List with Unique/Distinct Values (enhancing the Combo-Box with a few steps and a little code) David miller (dlmille) Intro Have you ever created a data validation list from a database field or spreadsheet column (e.g., Zip Codes or Co…
INDEX and MATCH can be used to great effect to replace HLOOKUP and VLOOKUP as it does not have the limitation of needing the data to be sorted so that the reference value is in the first column or row. It also has the ability to perform a bi-directi…
The viewer will learn how to create two correlated normally distributed random variables in Excel, use a normal distribution to simulate the return on different levels of investment in each of the two funds over a period of ten years, and, create a …
This Micro Tutorial demonstrate the bugs in Microsoft Excel for Mac with Pivot Charts.