gpt4 book ai didi

sql - 使用 Excel VBA 运行 SQL 查询

转载 作者:行者123 更新时间:2023-12-01 16:33:15 24 4
gpt4 key购买 nike

我对 SQL 和 VBA 相当陌生。我编写了一个 SQL 查询,我希望能够从 Excel 工作簿中的 VBA 子程序调用和运行该查询,然后将查询结果带入工作簿中。我在网上找到了一些潜艇(stackoverflow 和其他地方)声称可以这样做,但我无法理解它们,因为它们没有任何解释。例如,这是我在网上找到的一个子:

Sub ConnectSqlServer()

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String

' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _
"Initial Catalog=MyDatabaseName;" & _
"Integrated Security=SSPI;"

' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset

' Open the connection and execute.
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM Table1;")

' Check we have data.
If Not rs.EOF Then
' Transfer result.
Sheets(1).Range("A1").CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If

' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing

End Sub

首先,这可行吗?其次,我需要在子中替换什么(看起来像提供者、数据源、初始目录等)以及在哪里可以找到替换它们的信息?

我希望这个问题不会太令人困惑,感谢您的帮助!

最佳答案

下面是我目前用来将数据从 MS SQL Server 2008 提取到 VBA 中的代码。您需要确保您拥有正确的 ADODB 引用 [VBA 编辑器 -> 工具 -> 引用],并确保您已选中 Microsoft ActiveX Data Objects 2.8 Library,即选中的倒数第二行(我在 Windows 7 上使用 Excel 2010;您的 ActiveX 版本可能略有不同,但仍以 Microsoft ActiveX 开头):

References required for SQL

用于使用远程主机和用户名/密码连接到 MS SQL 的子模块

Sub Download_Standard_BOM()
'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 = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

'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 TOP 10 * FROM tbl_table"

'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

关于sql - 使用 Excel VBA 运行 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27385245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com