简体   繁体   中英

Run-time error while fetching data from SQL Server through Excel VBA

I am trying to fetch some data from a SQL server to excel using VBA. After researching on web, I have cobbled up a code and when I execute it, it throws a

Run-time error -'2147217900 (80040e14)':
Incorrect syntax near the keyword 'ON'.

From the error it seems that the error is detected due to some abnormality in the query. The query was provided by the DBA team and incorporates data from 2 different tables. I used the same query to manually export data from the database to excel and it works. I don't know why vba is throwing error. Any help will be appreciated. Thanks.

Sub sync_data_vba_sqlserver()

Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sqlQry As String, strCon As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
ActiveSheet.Cells.ClearContents

sqlQry = "SELECT A.PUMA_TSD_PollID AS ID, PUMA_TSD_FieldName AS Field_Name,PUMA_TSD_FieldValue AS Field_Value,PUMA_TSD_IPAddress AS IP_Address,PUMA_TSD_PollDate AS Poll_Date,PUMA_TSD_Channel AS Channel,PUMA_TSD_MachineName AS Machine_Name,PUMA_TSD_TestBedType AS TestBedType FROM [WWW_AUXMOD].[dbo].[tblPUMA_TSD_AVLLynx] A INNER JOIN [WWW_AUXMOD].[dbo].tblPUMA_TSD_AVLLynxData L ON A.PUMA_TSD_PollID = L.PUMA_CH_TSD_PollID ON A.PUMA_TSD_PollID = L.PUMA_CH_TSD_PollID WHERE PUMA_TSD_MachineName != 'ELMS_SYSTEM' AND PUMA_TSD_PollDate >= '6/2/19';"


'---- Replace below highlighted names with the corresponding values

strCon = "Provider=sqloledb;Data Source=ECCDB1503.MD3Q.FORD.COM;Initial Catalog=WWW_AUXMOD;Integrated Security=SSPI"

'---  Open   the above connection string.

con.Open (strCon)

    rs.Open sqlQry, con
    ActiveSheet.Cells(2, 1).CopyFromRecordset rs
    rs.Close

con.Close
Set rs = Nothing


End Sub

Expecting the data to be exported to Excel from SQL Server.

Pulled your query out and pasted here. Comment below, but removed ON and changed to AND. You had 2 ON's in a row.

SELECT A.PUMA_TSD_PollID AS ID, PUMA_TSD_FieldName AS Field_Name,PUMA_TSD_FieldValue AS Field_Value,PUMA_TSD_IPAddress AS IP_Address,PUMA_TSD_PollDate AS Poll_Date,PUMA_TSD_Channel AS Channel,
PUMA_TSD_MachineName AS Machine_Name,PUMA_TSD_TestBedType AS TestBedType 
FROM [WWW_AUXMOD].[dbo].[tblPUMA_TSD_AVLLynx] A 
INNER JOIN [WWW_AUXMOD].[dbo].tblPUMA_TSD_AVLLynxData L ON A.PUMA_TSD_PollID = L.PUMA_CH_TSD_PollID 
    -- change ON to AND HERE  (ON IS REMOVED)
    --AND A.PUMA_TSD_PollID = L.PUMA_CH_TSD_PollID (Redundant statement) 
WHERE PUMA_TSD_MachineName != 'ELMS_SYSTEM' 
AND PUMA_TSD_PollDate >= '6/2/19'

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