1

希望有人能帮助我解决我面临的问题。问题是我在同一个 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
4

1 回答 1

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")
于 2013-05-14T12:44:24.860 回答