2014-02-21 118 views
0

我試圖打開一個SQL存儲過程,它包含一個Select top 5 * form表格,並將數據加載到名爲Table3的Access表中。 如何將Command對象的ActiveConnection屬性設置爲使用當前的Access數據庫? 當我給它提供一個實際的連接字符串時,它說用戶已經鎖定它。 目前,它運行並打印輸出結果,但不插入值。它也不給我一個錯誤。VBA將數據從SQL服務器寫入Access數據庫

'Use this code to run the SP and extract all the records 
Public Sub ExecuteSPAsMethod2() 
Dim rsData As ADODB.Recordset 
Dim sConnectSQL As String 'to create connection to SQL Server 
Dim sConnectAccess As String 'to create connection with Access DB (may not be neccessary) 
Dim objCommand As ADODB.Command 'for INSERT results of SP into Access table 


'Creating the connection string to SQL server 
sConnectSQL = "Provider=SQLOLEDB;Data Source=MYSERVER; " & _ 
"Initial Catalog=SQLDatabase;Integrated Security=SSPI" 

'Creating the Connection object and Recordset object 
Set objConn = New ADODB.Connection 
Set rsData = New ADODB.Recordset 

'Opening the connection 
objConn.Open sConnectSQL 
'Execute the SP and give the results to the Recordset 
objConn.SurveyDataSP "4", rsData 

Do While Not rsData.EOF 
Debug.Print rsData!Stratum 
rsData.MoveNext 
Loop 

'Now write the data into Access Table 
'Create connection string to Access DB table 
'sConnectAccess = "Provider=Microsoft.ACE.OLEDB.12.0;" & _ 
       "Data Source=C:\Databse1.accdb;" & _ 
       "Mode = Share Exclusive" 

'Command object to be used for Access SQL query 
Set objCommand = New ADODB.Command 
'objCommand.ActiveConnection = sConnectAccess 

'Insert new record in the DB 
'Load the SQL string into the command object 
Do While Not rsData.EOF 
objCommand.CommandText = "INSERT INTO table3 (" & rsData!Stratum & ")" 
objCommand.Execute 
rsData.MoveNext 
Loop 


End Sub 
+0

http://msdn.microsoft.com/en-us/library/office/aa164887(v=office.10).aspx –

+0

不確定,但可能是您打開Access數據庫的方式有問題。如何評論所有Access的連接材料,並用「CurrentProject.Connection.Execute」插入替換代碼插入....「 –

回答

0

無需編寫如此大量的代碼並創建世界貧困。將執行命令保存爲傳遞查詢。

如:

Exec 4 

假設上述被稱爲SP1,那麼這段代碼將追加從上面的所有數據到本地表:

CurrentDb.Execute "INSERT INTO sp1Local select sp1.* from sp1" 

所以所有這些代碼都可以做到用一行VBA代碼。

相關問題