|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
大师们,本人小白,不会从Excel里查SQL,就用了笨一点的方法,录制宏来实现,查询是没有问题的,
录制的宏如下:但是根据我的理解,不应该这么多代码的,怎么把两次查询的代码合二为一,望老师们指点
Sub Macro2()
'
' Macro2 Macro
' 读取1
'
'第1、2列查询
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=Report;UID=Excel;PWD=excel;;APP=2007 Microsoft Office system;WSID=LHS-VM1;DATABASE=Datalog" _
, Destination:=Range("$A$1")).QueryTable
.CommandText = Array( _
"SELECT FloatTable.TagName, FloatTable.Val" & Chr(13) & "" & Chr(10) & "FROM Datalog.dbo.FloatTable FloatTable" & Chr(13) & "" & Chr(10) & "WHERE (FloatTable.TagName='li1') " _
)
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "表_查询来自_Report"
.Refresh BackgroundQuery:=False
End With
'第3、4列查询
Range("C1").Select
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=Report;UID=Excel;PWD=excel;;APP=2007 Microsoft Office system;WSID=LHS-VM1;DATABASE=Datalog" _
, Destination:=Range("$C$1")).QueryTable
.CommandText = Array( _
"SELECT FloatTable.TagName, FloatTable.Val" & Chr(13) & "" & Chr(10) & "FROM Datalog.dbo.FloatTable FloatTable" & Chr(13) & "" & Chr(10) & "WHERE (FloatTable.TagName='li2')" _
)
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "表_查询来自_Report_1"
.Refresh BackgroundQuery:=False
End With
End Sub
|
|