透過VBA執行SQL查詢

透過VBA執行SQL查詢

我是新來的,但每當我遇到 Excel 問題時,我總是會查看這個網站,到目前為止,你總是幫助我!現在我遇到了 VBA 問題:我想透過巨集「呼叫」SQL 查詢,因此基本上將來自查詢的資料複製並貼上到我的活動工作表中。

我嘗試了在該網站上找到的以下查詢(我不確定哪個是線程,因為我在自己詢問之前檢查了很多):

Sub sql()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = connString = "Driver={"mydriver"};Server="myserver";Database="mydatabase";UID="Myuserid";PWD="mypwd";Port=PortNum;SSL=true;Sslmode=Require"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "Select * from YYY.XXXX where date >='2020-03-01'"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

這是我得到的錯誤: 運行時錯誤

我嘗試用​​谷歌搜尋錯誤,發現我的 system32 中應該有伺服器;我查了“電腦管理”,但那裡沒有任何與 SQL 相關的內容。

你有什麼建議嗎?

如果還有關於同一問題的其他線程,我提前表示歉意,但到目前為止我找不到任何解決方案。

編輯:我沒有包含表格、使用者 ID 和密碼,因為它是我無法在線上分享的敏感資料;然而,我的問題是驅動程式、伺服器和資料庫;我不知道在那裡輸入什麼。另外,我應該將查詢的 URL (jdbc:...) 放在哪裡?

我通常使用 SQL Workbench 來獲取數據,並且每週都會將其複製並貼上到工作表中;這就是我希望巨集所做的事情。抱歉,如果我在編輯之前沒有正確解釋所有內容。

相關內容