在VBA中显示SQL查询以显示在电子表格中

时间:2016-09-21 15:03:53

标签: sql excel-vba vba excel

我正在尝试将此SQL查询显示在Excel工作表中,但每次运行宏都没有任何反应。我已经尝试添加一个带有单元格的范围,因此它可以显示在那里但没有任何反应。我也运行代码时没有错误消息。

Sub Run()

Call ConnectDB

Dim Cmd As ADODB.Command
Dim rcs As ADODB.Recordset
Dim SQL As String
Dim res() As String

Set Cmd = New ADODB.Command
Set Cmd.ActiveConnection = con

SQL = "select tl.id, al.price_crossing, al.price_exchange_fees, tl.charges_execution, tl.charges_mariana, tl.charges_exchange, tl.trade_date, un.value, tl.nb_crossing  from mfb.trade_leg AS tl " & _
"inner join mfb.trade t on t.id = tl.id_trade " & _
"inner join mfb.instrument i on t.id_instrument = i.id " & _
"inner join mfb.instrument_type it on it.id = i.id_instrument_type " & _
"inner join mfb.options o on o.id_instrument = i.id " & _
"inner join mfbref.mfb.underlying un on un.id = o.id_underlying " & _
"inner join mfb.allocation_leg al on al.id_trade_leg = tl.id " & _
"where tl.trade_date > '20160101' and t.state = 3 "

Cmd.CommandText = SQL
Set rcs = Cmd.Execute()


End Sub

1 个答案:

答案 0 :(得分:2)

你有一个良好的开端,但最终你留下了一个充满数据的开放记录集......你不会做任何事情。它不会在您的工作表中神奇地显示出来。您可以使用范围对象的方法.copyFromRecordset将记录集快速转储到工作表范围。

在代码的最后,END SUB放置之前:

 Sheet1.Range("A1").CopyFromRecordset rcs

然后,它会将您的查询结果转储到Cell A1处的Sheet1。

已更新,可以使用问题评论中提到的代码。执行Set R = Range("A2:A6")后,您可以使用.copyfromrecordset方法转储到R

 R.CopyFromRecordset rcs

为了彻底,您还可以遍历记录集,甚至是字段。加载记录集后,您可以执行以下操作:

 Dim f as Adodb.Field


 'loop through each record
 While now rcs.EOF 

     'loop through all the fields in this record:
     For each f in rcs.fields
         'get the fields name and value:
         debug.print f.name, f.value
     Next f

     'refer to a specific field (instead of looping through fields)
     debug.print rcs.Fields("price_crossing").name, rcs.Fields("price_Crossing").value

     'go to the next record
     rsc.movenext
 Loop