gpt4 book ai didi

sql - 使用vba将sql数据导入excel

转载 作者:行者123 更新时间:2023-12-03 02:10:46 25 4
gpt4 key购买 nike

我正在尝试将 SQL 表中的数据提取到 Excel 中。我已经使用数据源工具录制了一个宏。然而,我提取的数据量通常会使 Excel 崩溃。有没有办法在我的vba脚本中添加变量来限制从sql表中提取的数据?本质上是在 sql 中的 select 语句中添加一个 where 子句。

谢谢!

-肖恩

With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
"OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=10.22.30.215;Use Procedure for Prepare=1;Aut" _
, _
"o Translate=True;Packet Size=4096;Workstation ID="FakeName";Use Encryption for Data=False;Tag with column collation when possible=Fa" _
, "lse;Initial Catalog=FakeCatelog"), Destination:=Range("$A$1")). _
QueryTable
.CommandType = xlCmdTable
.CommandText = Array( _
"""FakeName""")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.SourceConnectionFile = _
"C:\UFakeFilePathodc"
.ListObject.DisplayName = "FakeName"
.Refresh BackgroundQuery:=False
End With
End Sub`

最佳答案

尝试连接到数据库并执行查询,而不是尝试将整个数据库拉入工作表中。这应该可以帮助您开始:
确保添加“Microsoft ActiveX Data Objects 6.0 Library”引用或运行此行一次:
ActiveWorkbook.VBProject.References.AddFromGuid "{B691E011-1797-432E-907A-4D8C69339129}", 6, 0

Sub QueryDB()
Dim dbName As ADODB.Connection
Dim dbResults As ADODB.Recordset
Set dbName = openDBConn("YOURDATABASE", "YourTable")
Set dbResults = dbName.Execute("SELECT * FROM YOURDATABASE")
While Not dbResults.EOF
'Do Something'
dbResults.MoveNext
Wend
End Sub

Function openDBConn(dataSource As String, table As String) As ADODB.Connection
Dim newDBConn As ADODB.Connection
Set newDBConn = New ADODB.Connection
newDBConn.CommandTimeout = 60
Dim strConn As String
strConn = "PROVIDER=SQLOLEDB;DATA SOURCE=" & dataSource & ";INITIAL CATALOG=" & table & ";INTEGRATED SECURITY=SSPI"
newDBConn.Open strConn
Set openDBConn = newDBConn
End Function

关于sql - 使用vba将sql数据导入excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13425642/

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