我有以下 vba,它从单元格 C10 开始读取 MCO,直到其为空,并将从 SQL 数据库中获取机器数、解密数和升级机器数。
这工作正常,但我无法获取相应行中的数据。目前它总是将数据写入 D10,因为我已经对其进行了硬编码,但我不确定如何让它递增或写入 MCO 已从中读取的同一行。如果记录集为空,我会遇到同样的问题。我想在 3 列中插入 0 0 0
非常感激任何的帮助
Sub Summary_Click()
Dim MyConnObj As New ADODB.Connection 'ADODB Connection Object
Dim myRecSet As New ADODB.Recordset 'Recordset Object
Dim sqlStr As String ' String variable to store sql command
Range("D9:F34").Select
Range("D9:F34").Clear
Range("C10").Select
Set myRecSet = New ADODB.Recordset
Do Until IsEmpty(ActiveCell)
strMCO = ActiveCell.Value
MyConnObj.Open _
"Provider = sqloledb;" & _
"Data Source=xxx;" & _
"Initial Catalog=xxx;" & _
"User ID=xxx;" & _
"Password=xxx;"
strqa = " SELECT Count (distinct DeviceData.machinename) As [Number Of Devices], sum(case buildstatus when 'Decrypted' then 1 else 0 end) Decrypted, sum(case buildstatus when 'Upgrading' then 1 else 0 end) Upgrading, SiteList.Region "
strqb = " FROM dbo.DeviceData JOIN dbo.SiteList ON dbo.DeviceData.CurrentSite = dbo.SiteList.SiteCode"
strqc = " where MCO = '" & strMCO & "' "
strqd = " group by DeviceData.Country, SiteList.Region"
sqlStr = strqa & strqb & strqc & strqd
myRecSet.Open sqlStr, MyConnObj, adOpenKeyset
ActiveCell.Offset(0, 1).Select
ActiveSheet.Range("D10").CopyFromRecordset myRecSet
'ActiveSheet.Range("D<10 + 1>).CopyFromRecordset myRecSet
If myRecSet.RecordCount = 0 Then
ActiveSheet.Range("D10, E10, F10") = "0"
End If
ActiveCell.Offset(1, -1).Select
MyConnObj.Close
Loop
End Sub