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