2017-06-14 55 views
0

連接VBA時到SQL Server我有麻煩:VBA連接到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 

我只是想選擇一個名爲[dbo].[Version]表中的所有值,但是當我執行它,我得到一個錯誤:

Compile error: Expected Function or Variable'

並用rs.Open線被突出顯示。

你能幫我解決這個問題嗎?

回答

0

Open是一種方法,不能用=進行設置。

你可能想是這樣的:

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

一旦調用Open,那麼你可以通過使用EOF屬性和MoveNext方法Recordset的行迭代:

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 
0

更改代碼如下:

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是一個基於零的集合,這意味着第一個字段爲0,而不是1. 您可以通過rs.Fields(1),rs.Fields(2)等獲取後續字段。或者,您可以使用字段名稱,使用語法rs.Fields(「MyFieldName」)。

使用字符串命令(「SELECT * FROM ..」)時注意CommandType是adCmdText。 Recordset的語法是SET rs = cmd.Execute。你也必須在你的循環中調用MoveNext,否則你會陷入循環中!