一个工作表中的多个SQL查询输出

时间:2013-05-14 11:57:55

标签: excel vba excel-vba

希望有人会帮助我解决我面临的问题。问题是我在同一个Excel工作表中输出多个SQL查询时遇到了困难。

通过下面的代码,我能够获得带有列标题的一个/单个SELECT查询输出的输出。现在我想在同一工作表中显示多个SELECT查询输出。

代码---

Sub databases()

Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Dim sSQL1 As String


sSQL1 = "SELECT SUM(number_submitted)as NUMBER_SUBMITTED," & _
"MGR_GRP_ID,SERVICE_CI_ID,LOCATION_ID from CHANGE_REQUEST_ENUM_F where              ENUM_FIELD_CD=11834 and ENUM_VALUE in (10,11)" & _
"group by MGR_GRP_ID,SERVICE_CI_ID,LOCATION_ID"

'sSQL2 = "select * from change_request_f"

Set cn = New ADODB.Connection

Sheets("sheet4").Select
Selection.ClearContents

cn.Open "Provider=SQLOLEDB.1; UID=USERID;PWD=PASSWORD;Initial catalog=BMCDI_DWH;Data             Source=vw-pun-atm-qa26"

Set rs = New ADODB.Recordset

rs.CursorLocation = adUseClient
rs.Open sSQL1, cn, adOpenForwardOnly, adLockReadOnly, adCmdText
'check content of rs
If rs.EOF Then
MsgBox ("record set is empty. rs.EOF = " & rs.EOF)
Else
MsgBox ("total records: " & rs.RecordCount)
Range("A1").Select
For Each qf In rs.Fields
Range("a1").Offset(0, coloffset).Value = qf.Name
'Range("a1").Offset(1, 0).Value = qf.Name
coloffset = coloffset + 1
Next qf
Range("A2").CopyFromRecordset rs
rs.Close
Set rs = Nothing
End If
End Sub

1 个答案:

答案 0 :(得分:0)

我会把它分成另一个子。

 Sub writeRs(rs as ADODB.Recordset, startRange as Range)
 'All your code here to place the recordset
 'The only change would be for the use of startRange
 'This you would pass the upper left cell that you want the recordset to be written to.

 End Sub

然后您可以使用两个记录集对象。 rs1rs2并致电您的子

 rs1.Open sql1, cn...
 rs2.Open sql2, cn...

 ''Check for empties

 writeRs rs1, Range("A1")
 writeRs rs2, Range("A10")