在一个Worksheet中输出多个SQL查询

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

我会分解成另一个子。

  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 

然后你可以使用两个logging集对象。 rs1rs2并调用你的子

  rs1.Open sql1, cn... rs2.Open sql2, cn... ''Check for empties writeRs rs1, Range("A1") writeRs rs2, Range("A10")