2016-11-23 101 views
0

我試圖建立Excel和SQL之間的鏈接,但是運行VBA代碼時出現以下錯誤消息「命令文本未設置爲命令對象」。我對VBA很陌生,有誰能看到我哪裏出錯了嗎?連接SQL和Excel

僅供參考我在Sheet2.Range( 「A2」)

這裏是我的VBA代碼複製的SQL代碼。

Sub Update() 

Dim link As New ADODB.Connection 
Dim login As String 
Dim SQLSyntax As String 
Dim Basket As New ADODB.Recordset 

login = "DRIVER=SQL Server Native Client 10.0;SERVER=xxxxxx;UID=sa;PWD=xxxxx;APP=2007 Microsoft Office system;WSID=PC3;DATABASE=ST_L1;" 
SQLSyntax = Sheet2.Range("A2").Text 

link.Open login 
Basket.Open SQLSyntax, link 

Basket.Close 
link.Close 

End Sub 

我的SQL代碼(在SQL中工作正常)。

Select P.spn as [Number],P.[Group],P.Name, isnull(T.Calls,0) as [Calls in last 2 months (excluding internals)], isnull(L.[Internal Calls],0) as [Internal Calls] ,isnull(M.[Last call],0)as [Last call] from ST_L1.dbo.Numbers P 
left join 
(Select COUNT(*)as [Calls],SPN from ST_L1.dbo.Main where CLI not in (Select CLI from ST_L1.dbo.internalCLI) 
and start between convert (date,getdate()-62)and convert (date,getdate()) 
group by SPN)T on T.SPN = P.spn 
left join (Select max(start)[Last call],SPN from ST_L1.dbo.Main 
group by SPN)M on M.SPN = P.spn 
left join 
(Select COUNT(*)as [Internal Calls],SPN from ST_L1.dbo.Main where CLI in (Select CLI from ST_L1.dbo.internalCLI) 
and start between convert (date,getdate()-62)and convert (date,getdate()) 
group by SPN)L on L.SPN = P.spn 
where LEFT(P.spn,4) not in ('0870') and P.[Group] in 
('BlaBla', 'BlaBla2') 
order by T.Calls asc,M.[Last call] 
+0

哪條線返回錯誤?它是否是Basket.Open SQLSyntax,link'? –

+0

是的,對不起,Basket.Open SQLSyntax,鏈接返回錯誤。 –

回答

0

永遠不會打開記錄集?

Set basket = link.Execute("SELECT * FROM Table1;") 
+0

嗨@DougCoats感謝您的回覆。我在上面的VBA代碼中用'Set Basket = link.Execute(SQLSyntax)'替換了'Basket.Open SQLSyntax,link'。它導致相同的「命令文本沒有設置爲命令對象」錯誤不幸的是:( –

+0

@ASuperTramp也許你應該在Visual Studio中直接解析SQL,而不是拉動表單工作表?可能會出現格式化問題 –

+1

This現在已經修復,這是一個格式問題,非常感謝你的幫助。 –