VBA学习资料分享-5
作者:互联网
工作中经常要从数据库把数据跑出来放到EXCEL上,才能进行下一步的操作,那么除了ADO,还有什么方法可以导入数据库数据呢?
推荐使用QueryTable对象
Dim qt As querytable constr = "OLEDB;Provider=SQLOLEDB;Server=DCDRDB601\dminputdb;Trusted_Connection=yes" '注意比ADO的连接字符串开头多了个“OLEDB;” sql="select * from ......" Set qt = ActiveSheet.QueryTables.Add(constr, Range("a1"), sql) qt.Refresh
使用QueryTable方法的代码比较简洁,比较ADO省了数据库的连接和设置,还有字段名的读取,QueryTable可以统一将字段名和结果一并返回到以指定的单元格为左上角的区域中,非常方便。但是使用QueryTable建立的数据库连接会一直存在工作表中,每执行一次就建立一次连接,如下图
要删除掉以前的连接,可以先运行以下一段代码
While ActiveSheet.QueryTables.Count > 0 ActiveSheet.QueryTables(1).Delete Wend
或者
While ActiveWorkbook.Connections.Count > 0 ActiveWorkbook.Connections(1).Delete Wend
还可以将QueryTable“拆开”执行,即先“Query”,再写入“Table”
ActiveWorkbook.Queries.Add _ Name:="Query1", _ Formula:= _ "let" & Chr(13) & "" & Chr(10) & _ " Source = Sql.Database(""server_name"", ""db_name"", [Query=""SELECT TOP 1000 FROM ......""])" & Chr(13) & "" & Chr(10) & _ "in" & Chr(13) & "" & Chr(10) & " Source"
其中,Chr(13) & "" & Chr(10)可以理解为换行符,注意双引号需要double
With ActiveSheet.ListObjects.Add( _ SourceType:=0, _ Source:= _ "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Query1;Extended Properties=""""" _ , Destination:=ActiveSheet.Range("$A$1") _ ).querytable .CommandType = xlCmdSql .CommandText = Array("SELECT * FROM [Query1]") .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .PreserveColumnInfo = True .ListObject.DisplayName = "Query1" .Refresh BackgroundQuery:=False End With
同理,建立的数据库连接会一直存在工作表中,每执行一次就建立一次连接,要删除掉以前的连接,可以先运行以下一段代码
While ActiveWorkbook.Queries.Count > 0 ActiveWorkbook.Queries(1).Delete Wend
标签:VBA,False,ActiveSheet,QueryTable,ActiveWorkbook,Chr,资料,分享,True 来源: https://www.cnblogs.com/JTCLASSROOM/p/10880818.html