Вы находитесь на странице: 1из 22

VBA for Beginners

VBA Tips and Tutorials for Beginners

« 2.29 Password Protecting Queries with Access VBA

VBA/Excel Connecting Excel to Access using


VBA
Video demonstrates how to pull directly from Access and put to an
Excel worksheet.

Duration : 0:5:4

[youtube KMeQzxFk-To]
Facebook
Twitter
DiggIt
Technorati
Blinklist
Furl
reddit

This entry was posted on Wednesday, August 4th, 2010 at 3:46 am and is filed underAccess VBA for beginners.

You can follow any responses to this entry through the RSS 2.0feed. You can leave a response, or trackback from

your own site.

7 Responses to “VBA/Excel Connecting Excel to Access using


VBA”

1. aceaceaceJOKER on August 4th, 2010 at 3:46 am

I figured it out. …
I figured it out. Just edit the recordset part with this. Define column at the top.
StartRow = 1
For column = 0 To rs.Fields.count – 1
Cells(StartRow, column + 1) = rs.Fields(column).Name
Next
column = 0
StartRow = 2
Do Until rs.EOF
For column = 0 To rs.Fields.count – 1
Cells(StartRow, column + 1) = rs.Fields(column).Value
Next
rs.MoveNext
StartRow = StartRow + 1
Loop

2. aceaceaceJOKER on August 4th, 2010 at 3:46 am

Thanks for the …


Thanks for the tutorial Exceltip. I’ve been trying to figure out how you would code it
to where you would include all the column names at the top of the spreadsheet and
list all the data rows under each column name. Please help thanks.

3. exceltip on August 4th, 2010 at 3:46 am

Put this in the …


Put this in the connection string (change password and username accordingly):

;Uid=Admin;Pwd=mypassword;

4. sandhollownight on August 4th, 2010 at 3:46 am

Whats the syntax if …


Whats the syntax if my db has a login and password?

5. exceltip on August 4th, 2010 at 3:46 am

Below is the …
Below is the connection string (can be hard to read):
‘—————————
Dim con As New ADODB.Connection
Dim rc As New ADODB.Recordset
‘Drive code for access
con.ConnectionString = “DBQ=c:\temp\db1.mdb; ” & _
“DRIVER={Microsoft Access Driver (*.mdb)}”
‘Open the connection
con.Open

Set rc.ActiveConnection = con

6. exceltip on August 4th, 2010 at 3:46 am

You need to select …


You need to select “WATCH IN HIGH QUALITY.”

7. foxymophandlemaaa on August 4th, 2010 at 3:46 am

Sadly we cant see …


Sadly we cant see any code, its too blury

Leave a Reply
Name (required)

Mail (will not be published) (required)

Website

Submit Comment


Categories

o Access VBA for beginners


o Excel VBA for Beginners
o VBA for Beginners
Tags

a1 reference style Accessaction basic candy cells property code codesExcel excel
guides excel help excel macros excel teacherexcel tips excel tricks excel tutorials free

macrosgameshark Hello Learn VBA macro macrosmasterball Microsoftmicrosoft excel


2007Password pokemonpokemonhelpstart range

property rare recordingrecordset replay sapphireselect cells with

macro shinyspreadsheets SQL tutorialVB VBA visual workbooks worksheets World

Recent Posts

o VBA/Excel Connecting Excel to Access using VBA


o 2.29 Password Protecting Queries with Access VBA
o 2.32 Queries Using SQL And VBA in Access
o Microsoft Access Advanced: RecordSets to Access Data in VBA
o 2.26 Password Login Form / screen using VBA in Access
Blogroll

o Excel for Dummies


o Excel Video Tutorial
o learn excel
o Newegg Coupon Code
o Newegg Promo
o Spreadsheets for Dummies
o VBA for Beginners
Copyright © VBA for Beginners - Powered by WordPress
ProSense theme created by Dosh Dosh and The Wrong Advices.

Timesheets MTS Software


..... your source for accurate, cost effective, and easy to use Global Site Australian
timesheet software Site

Timesheets MTS Software - Visual Basic 6 ADO Tutorial

Scope

This tutorial aims to provide an intermediate Visual Basic 6 user with the basic skills required
to retrieve and manipulate data from many commercial databases and any ODBC compliant
database. It assumes that those reading it have an understanding of the Object Oriented
methodology of Visual Basic 6, and also of the typical programming structures found in Visual
Basic. For example, no explanation of what a method is will be given, and it will be assumed
that readers will know how the For Each Obj in Collection structure works.
Finding this tutorial helpful? Why not

to help cover the bandwidth it chews up? It's the


most popular page on this site bar none!
Introduction

Visual Basic 6 obsoletes the previously used database access technology provided by Jet and
provides a new one known as ADO or Active Data Objects. This technology allows users to
access data easily from many existing databases (such as Access or Paradox) or from ODBC
compliant databases like Oracle or MS SQL Server. Using ADO is quite simple and allows
programmers to provide flexible database front ends to users that are reliable and include
many features. As a VB6 programmer ADO is important to know as most commercial VB
programming exercises involve providing a front end to some sort of database.
Following are some of the key objects found in the ADO object model and some of their key
methods and properties.
Connection Object

This object represents an open connection to the data source. This connection can be a local
connection (say App.Path) or can be across a network in a client server application. Some of
the methods and properties of this object are not available depending on the type of data
source connected to.

Key Properties

Name Data Type Description

ConnectionString String Defines in string form the location of the data source
you wish to connect to. Key fields in the string you will
use are the "Provider=" and the "Data Source=" fields.
You may also use the "Mode=" field. See descriptions of
those properties for a more detailed view of each one.
Some examples of connection strings follow:

Data Source=c:\test.mdb;Mode=Read|
Write;Persist - Connects to an Access database with
read/write/persist permissions

driver={SQL Server)
server=bigsmile;uid=sa;pwd=pwd;database=pub
s- Connects to an SQL Server database called bigsmile
as user sa with password pwd to database pubs.

A string defining the provider of a connection object. An


example follows:

Provider String
Provider=Microsoft.Jet.OLEDB.4.0 -This string
connects to a MS Jet 4.0 compliant database (an Access
DB for example.)

Sets (or returns) the permissions for modifying data


across the open connection. Available permissions
Mode connectModeEnum
include Read, Write, Read/Write, and various
Share/Deny types.

Sets the location of the cursor engine. You can select


cursorLocationEnu
CursorLocation client side or server side, for simpler databases (like
m
Access) client side is the only choice.

ConnectionTimeou Time in seconds that a connection will attempt to be


Long
t opened before an error is generated.

Time in seconds that an command will attempt to be


CommandTimeout Long
executed before an error is generated.

Key Methods
Name Description

Close Closes an open connection.

Open Opens a connection with the settings in the ConnectionString property.


Command Object

A command object specifies a specific method you intend to execute on or against the data
source accessed by an open connection.

Key Properties
Name Data Type Description

conConnection as Defines the Connection object the command belongs


ActiveConnection
ADODB.Connection to.

Contains the text of the command you want to execute


against a data source. This can be a table name, a
CommandText String valid SQL string, or the name of a stored procedure in
the data source. Which one you use is determined by
the CommandType property.

Defines the type of the command. The three most


commonly used would be adCmdText, adCmdTable,
and adCmdStoredProc. The setting adCmdText causes
the CommandText string to be evaluated as an SQL
string. The setting adCmdTable causes the
CommandType commandTypeEnum
CommandText string to be evaluated as a table name
and will return the all of the records and columns in a
table. The setting adCmdStoredProc causes the
CommandText string to be evaluated as a stored
procedure in the data source.

Key Methods
Name Description

Executes the query, SQL statement, or stored procedure specified in the


Execute
CommandText property and returns a RecordSet object.

RecordSet Object

The RecordSet object represents a complete set of records from an executed command or
from an underlying base table in the database. A key thing to note is that a RecordSet object
references only one record at a time as the current record.
Key Properties
Name Data Type Description

This sets or returns the location of the cursor engine for


CursorLocationEnu the database. The options are client side and server side,
CursorLocation
m for less advanced databases like Access you may only be
able to select client side.

Sets the cursor type. CursorType typically determines


when and to whom database changes are immediately
CursorType CursorTypeEnum
visible to. For client side cursor locations only one type of
CursorType is available, adOpenStatic.

End Of File and Beginning Of File. When at the first record


of an open RecordSet BOF will be true, when at the last
EOF will be true. If you ever return a RecordSet with no
EOF and BOF Boolean
records then EOF and BOF will be true. This provides an
ideal way of testing if any records have been returned by a
query.

Returns a collection of the field objects for an open record


set. Database fields can be accessed by their name using
the RecordSet!FieldName schema, by their index
RecordSet.Fields(intIndex) or sometimes by their name
Fields Collection from the fields collection RecordSet.Fields("FieldName"). I
find in the situation where you know a database structure
that the RecordSet!FieldName method is best, where
structure is not known, then the
RecordSet.Fields(intIndex) may be best.

sets the lock type on records when they are open for
LockType LockTypeEnum editing. If a client side cursor location is selected then only
optimistic and batch optimistic locking are available.

Returns the number of records in an open RecordSet. If for


RecordCount Long some reason ADO cannot determine the number of records
then this will be set to -1.
Key Methods
Name Description

Sets up an open record set to add a new record, once the required values have
AddNew
been set call the Update (or UpdateBatch) method to commit the changes.

Closes an open RecordSet object, make sure that any changes are committed
Close using the Update (or UpdateBatch) method before closing or an error will be
generated.

Causes an open RecordSet object to move to the next record in the collection, if
MoveNext
the current record is the last record then EOF is set to true.

MoveFirst Causes an open RecordSet object to move to the first record in the collection.

MoveLast Causes an open RecordSet object to move to the last record in the collection.

Opens the RecordSet, typically this is done with a valid Command object that
Open
includes the command text (or SQL) to get the records you want.

Update Causes any changes made to the current record to be written to disk.

Causes any changes you have made in batch mode to be written to disk. The way
UpdateBatch to use batch updates is to open the RecordSet object with the LockType
adLockBatchOptimistic.

Putting It All Together

I like to think of using ADO as a three step process

• Define and open a Connection to a data source


• Decide what data you need from the data source and define Command objects that
will retrieve this data.
• Retrieve the data you require by executing the command objects and manipulate the
data using RecordSet objects.

To start using ADO create a new Standard EXE project in your VB6 environment. You'll need to
add a reference to the ADO library using the Project -> References menu and selecting the
"Microsoft ActiveX Data Objects 2.5 Library" or the "Microsoft ActiveX Data Objects 2.6
Library". Then on the form add a single command button and add the code below to the click
event of the button.
Save the project and then open Microsoft Access and create a new database called
"database.mdb" in the directory where you have saved your VB project. Add a table called
"tabTestTable" to the database. Add two columns to this table with a text data type, the
column names do not matter. Add a couple of records to the table with some values in the
columns.
Then you can safely run your project and see the results.
If you dont want to do this I have created a VB project that includes all of this that can
be downloaded. Just unzip this to a directory and open the project in Visual Studio and try it
out.
Got questions? Feel free to ask me at questions@timesheetsmts.com Why not

to help cover the bandwidth this page chews up and you'll be


much more likely to get an answer!
Private Sub Command1_Click()

'Define the three objects that we need,


' A Connection Object - connects to our data source
' A Command Object - defines what data to get from the data source
' A RecordSet Object - stores the data we get from our data source

Dim conConnection As New ADODB.Connection


Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset

'Defines the connection string for the Connection. Here we have used
fields
'Provider, Data Source and Mode to assign values to the properties
' conConnection.Provider and conConnection.Mode

conConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Da
ta Source=" & _
App.Path & "\" & "database.mdb;Mode=Read|Write"

'Define the location of the cursor engine, in this case we are opening
an Access database
'and adUseClient is our only choice.

conConnection.CursorLocation = adUseClient
'Opens our connection using the password "Admin" to access the databa
se. If there was no password
'protection on the database this field could be left out.

conConnection.Open

'Defines our command object

' .ActiveConnection tells the command to use our newly created command
object.
' .CommandText tells the command how to get the data, in this case the
command
' will evaluate the text as an SQL string and we will re
turn all
' records from a table called tabTestTable
' .CommandType tells the command to evaluate the .CommandText property
as an SQL string.

With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM tabTestTable;"
.CommandType = adCmdText
End With

'Defines our RecordSet object.

' .CursorType sets a static cursor, the only choice for a client side
cursor
' .CursorLocation sets a client side cursor, the only choice for an
Access database
' .LockType sets an optimistic lock type
' .Open executes the cmdCommand object against the data source and s
tores the
' returned records in our RecordSet object.

With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
'Firstly test to see if any records have been returned, if some have
been returned then
'the .EOF property of the RecordSet will be false, if none have been
returned then the
'property will be true.

If rstRecordSet.EOF = False Then

'Move to the first record

rstRecordSet.MoveFirst

'Lets move through the records one at a time until we reach the last
record
'and print out the values of each field

Do

'Access the field values using the fields collection and print th
em to a message box.
'In this case I do not know what you might call the columns in yo
ur database so this
'is the safest way to do it. If I did know the names of the colu
mns in your table
'and they were called "Column1" and "Column2" I could reference t
heir values using:

' rstRecordSet!Column1
' rstRecordSet!Column2

MsgBox "Record " & rstRecordSet.AbsolutePosition & " " & _


rstRecordSet.Fields(0).Name & "=" & rstRecordSet.Fields(0) & "
" & _
rstRecordSet.Fields(1).Name & "=" & rstRecordSet.Fields(1)

'Move to the next record

rstRecordSet.MoveNext
Loop Until rstRecordSet.EOF = True

'Add a new record


With rstRecordSet
.AddNew
.Fields(0) = "New"
.Fields(1) = "Record"
.Update
End With

'Move back to the first record and delete it

rstRecordSet.MoveFirst
rstRecordSet.Delete
rstRecordSet.Update

'Close the recordset

rstRecordSet.Close
Else
MsgBox "No records were returned using the query " & cmdCommand.Com
mandText
End If

'Close the connection

conConnection.Close

'Release your variable references

Set conConnection = Nothing


Set cmdCommand = Nothing
Set rstRecordSet = Nothing
End Sub

Generated using PrettyCode.Encoder

Products Support Free Software Contact Us About Us

Site Map
Option Explicit

Private Sub cmdOpen_Click()


Dim Conn1 As New adodb.Connection
Dim Cmd1 As New adodb.Command
Dim Errs1 As Errors
Dim Rs1 As New adodb.Recordset

Dim i As Integer
Dim AccessConnect As String

' Error Handling Variables


Dim errLoop As Error
Dim strTmp As String

AccessConnect = "Driver={Microsoft Access Driver (*.mdb)};" & _


"Dbq=nwind.mdb;" & _
"DefaultDir=C:\program files\devstudio\vb;" & _
"Uid=Admin;Pwd=;"

'---------------------------
' Connection Object Methods
'---------------------------

On Error GoTo AdoError ' Full Error Handling which traverses


' Connection object

' Connection Open method #1: Open via ConnectionString Property


Conn1.ConnectionString = AccessConnect
Conn1.Open
Conn1.Close
Conn1.ConnectionString = ""

' Connection Open method #2: Open("[ODBC Connect String]","","")


Conn1.Open AccessConnect
Conn1.Close

' Connection Open method #3: Open("DSN","Uid","Pwd")


Conn1.Open "Driver={Microsoft Access Driver (*.mdb)};" & _
"DBQ=nwind.mdb;" & _
"DefaultDir=C:\program files\devstudio\vb;" & _
"Uid=Admin;Pwd=;"
Conn1.Close

'--------------------------
' Recordset Object Methods
'--------------------------

' Don't assume that we have a connection object.


On Error GoTo AdoErrorLite

' Recordset Open Method #1: Open via Connection.Execute(...)


Conn1.Open AccessConnect
Set Rs1 = Conn1.Execute("SELECT * FROM Employees")
Rs1.Close
Conn1.Close

' Recordset Open Method #2: Open via Command.Execute(...)


Conn1.ConnectionString = AccessConnect
Conn1.Open
Cmd1.ActiveConnection = Conn1
Cmd1.CommandText = "SELECT * FROM Employees"
Set Rs1 = Cmd1.Execute
Rs1.Close
Conn1.Close
Conn1.ConnectionString = ""

' Recordset Open Method #3: Open via Command.Execute(...)


Conn1.ConnectionString = AccessConnect
Conn1.Open
Cmd1.ActiveConnection = Conn1
Cmd1.CommandText = "SELECT * FROM Employees"
Rs1.Open Cmd1
Rs1.Close
Conn1.Close
Conn1.ConnectionString = ""

' Recordset Open Method #4: Open w/o Connection & w/Connect
String
Rs1.Open "SELECT * FROM Employees", AccessConnect,
adOpenForwardOnly
Rs1.Close

Done:
Set Rs1 = Nothing

Set Cmd1 = Nothing


Set Conn1 = Nothing

Exit Sub

AdoError:
i = 1
On Error Resume Next

' Enumerate Errors collection and display properties of


' each Error object (if Errors Collection is filled out)
Set Errs1 = Conn1.Errors
For Each errLoop In Errs1
With errLoop
strTmp = strTmp & vbCrLf & "ADO Error # " & i & ":"
strTmp = strTmp & vbCrLf & " ADO Error # " & .Number
strTmp = strTmp & vbCrLf & " Description " & .Description
strTmp = strTmp & vbCrLf & " Source " & .Source
i = i + 1
End With
Next

AdoErrorLite:
' Get VB Error Object's information
strTmp = strTmp & vbCrLf & "VB Error # " & Str(Err.Number)
strTmp = strTmp & vbCrLf & " Generated by " & Err.Source
strTmp = strTmp & vbCrLf & " Description " & Err.Description

MsgBox strTmp

' Clean up gracefully without risking infinite loop in error


handler
On Error GoTo 0
GoTo Done
End Sub
Experience a more beautiful web

Don't show me this again


United States Change | All Microsoft Sites

Microsoft Support

• Support Home

• Solution Centers

• Advanced Search

• Buy Products

Other Resources
Other Support Sites
Community
Get Help Now
Article ID: 308047 - Last Review: March 29, 2007 - Revision: 4.4 Article Translations
(‫الشرق الوسط )العربية‬
How to open ADO Connection and Recordset objects by using
Visual Basic .NET
View products that this article applies to.
This article was previously published under Q308047
Caution ADO and ADO MD have not been fully tested in a Microsoft .NET Framework environment.
They may cause intermittent issues, especially in service-based applications or in multithreaded View related content
applications. The techniques that are discussed in this article should only be used as a temporary measure
during migration to ADO.NET. You should only use these techniques after you have conducted • Walkthrough: Creating COM
complete testing to make sure that there are no compatibility issues. Any issues that are caused by using Objects with Visual Basic
ADO or ADO MD in this manner are unsupported. For more information, see the following article in the • How To Create ADO
Microsoft Knowledge Base: Disconnected Recordsets in ASP
840667 You receive unexpected errors when using ADO and ADO MD in a .NET Framework Using VBScript ...
application • How To Open ADO Connection
and Recordset Objects
On This Page • AdomdConnection Class
(Microsoft.AnalysisServices.Ad
omdClient)
Expand all | Collapse all

SUMMARY • TableAdapters and Object


Binding - Bridging the gap - The
Visual ...
This article demonstrates different ways to create ActiveX Data Objects

(ADO) Connection andRecordset objects in Visual Basic .NET. Note that these objects are ADO

objects and not ADO.NET objects.


Search related topics
• Creating objects in Visual
basic
• Creating objects in visual
basic.NET
Back to the top • Ado in .NET 2008
• Build connection string
visual basic
Create ADO Connection and Recordset Objects in Visual Basic .NET
• VBA ADO recordset
example
1. Create a new Visual Basic .NET Windows Application project. Form1 is created by default.

2. From the Project menu, click Add Reference.

3. On the COM tab, click Microsoft ActiveX Data Objects 2.x Library, and then clickSelect.

4. Add the following code to the General Declarations section of Form1:


5. Dim cn As New ADODB.Connection()
Related Support Centers
6. Dim rs As New ADODB.Recordset()
7. Dim cnStr As String • Visual Basic .NET 2003
8. Dim cmd As New ADODB.Command()
• Visual Basic .NET 2002

9. The following code illustrates two different methods to open an ADO Connection object.

Each of these methods connect to a Microsoft SQL Server Pubs database and can be added to

the Form1 Load event.

Note User ID <user name> must have permissions to perform these operations on the

database.
10. ' Modify this connection string to reflect your
server and logon information.
11. ' Store the connection to a variable to be used
throughout this example.
12. cnStr = "Provider=SQLOLEDB;Initial Catalog=Pubs;Data
Source=servername;" & _
13. "User ID=<username>;Password=<strong password>;"
14.
15. ' 1. Connect through the Connectionstring property.
16. cn.ConnectionString = cnStr
17. cn.Open()
18. cn.Close()
19.
20. ' 2. Connect through the Connection object's Open
method.
21. cn.Open(cnStr)
22. cn.Close()

23. The following code illustrates three different ways to open an ADO Recordset object. Each of
these methods connect to a Microsoft SQL Server Pubs database and can be added to the

Form1 Load event:


24. ' 1. Open Recordset through the Execute method of
the Connection object.
25. cn.Open(cnStr)
26. rs = cn.Execute("Select * from Authors")
27. rs.Close()
28. cn.Close()
29.
30. ' 2. Open Recordset through the Command.Execute
method.
31. cn.Open(cnStr)
32. cmd.ActiveConnection = cn
33. cmd.CommandText = "Select * from Authors"
34. rs = cmd.Execute
35. rs.Close()
36. cn.Close()
37.
38. ' 3. Open Recordset without a Connection object.
39. rs.Open("Select * from Authors", cnStr)
40. rs.Close()
41.
42. ' Release the objects to free memory.
43. rs = Nothing
44. cn = Nothing

45. Modify the Connection string where indicated to properly connect to your SQL Server.

46. Press the F11 key to step through the code, and notice the different ways to create
aConnection or Recordset object.

NOTE: When you set the Recordset object's ActiveConnection property to an actual string (as opposed

to a Connection object), as follows


rs.ActiveConnection = "Provider=SQLOLEDB;Initial
Catalog=Pubs;Data Source=servername;User
ID=<username>;Password=<strong password>;

the following build error occurs in Visual Basic .NET:

Value of type 'String' cannot be converted to 'ADODB.Connection'.

Back to the top

REFERENCES

For additional information, click the article number below to view the article in the Microsoft

Knowledge Base:

168336 How To Open ADO Connection and Recordset Objects

For more general information about Visual Basic .NET and ADO.NET, see the following Usenet

newsgroups:

microsoft.public.dotnet.languages.vb

microsoft.public.dotnet.framework.adonet

For more information about the advantages of the new DataReader and DataAdapter objects in

ADO.NET, visit the following Microsoft Developer (MSDN) Web site:

ADO.NET for the ADO Programmer


http://msdn2.microsoft.com/en-us/library/ms973217.aspx

Back to the top

APPLIES TO

Back to the top


Keywords: kbhowtomaster KB308047

Back to the top

Provide feedback on this information


Did this information solve your problem?
Yes

No
I don't
know

Was this information relevant?


Yes

No

How much effort did you personally put forth to use this article?
Very low

Low

Moderate
Hig
h
Very high

What can we do to improve this information?

To protect your privacy, do not include contact information in your feedback.

Get Help Now


Contact a support professional by E-mail, Online, or Phone

Microsoft Support

Вам также может понравиться