简体   繁体   中英

VBA connecting to SQL Server

I am having trouble when connecting VBA to SQL Server:

Sub ConnectSQLServer()

Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String

Dim par As ADODB.Parameter
Dim strSQL As String

strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"

Set conn = New ADODB.Connection
conn.Open strConn

Set cmd = New ADODB.Command
cmd.CommandText = "dbo.Version"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn

rs.Open = "SELECT * FROM [dbo].[Version]"

cmd.Execute rs
Set conn = Nothing
Set cmd = Nothing


sConnString = ""
End Sub

I just want to select all values from the table named [dbo].[Version] , but when I execute it, I get an error:

Compile error: Expected Function or Variable'

and the line with rs.Open is highlighted.

Would you help me to solve this problem?

Open is a method, and cannot be set with an = .

You probably want something like this:

rs.Open "SELECT * FROM [dbo].[Version]", conn

Once you have called Open , then you can iterate through the Recordset's rows using the EOF property and the MoveNext method:

Do While Not rs.EOF
    Debug.Print rs.Fields(1)
    'You could also use rs!FieldName, where FieldName is the name of a column
Loop

Change your code to the following:

Set cmd = New ADODB.Command
cmd.CommandText = "SELECT * FROM [dbo].[Version]"
cmd.CommandType = adCmdText
cmd.ActiveConnection = conn

Set rs = cmd.Execute

Do While Not rs.EOF
    'do something with rs.Fields(0) '
    rs.MoveNext
Loop
Set conn = Nothing
Set cmd = Nothing

rs.Fields is a zero based collection that means that the first field is 0, not 1. You can get subsequent fields by rs.Fields(1), rs.Fields(2) etc. Or you can use Field names, with the syntax rs.Fields("MyFieldName").

Note when using a string command ("SELECT * FROM ..") the CommandType is adCmdText. The syntax for the Recordset is SET rs = cmd.Execute. Also you must invoke MoveNext in your loop, otherwise you get stuck in the loop!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM