我有以下vba,它从C10单元格开始读取MCO,直到它为空,并从SQL数据库中获取机器数量,解密数量和升级机器。
工作正常但我在相应的行中获取数据时遇到问题。目前它始终将数据写入D10因为我已对其进行了硬编码,但我不确定如何将其增加或写入已读入MCO的同一行。如果记录集为空,我遇到同样的问题。我想将0 0 0插入3列
非常感谢任何帮助
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
答案 0 :(得分:0)
将Excel工作表包含为连接表可能最简单。例如:
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
''Not the best way to get the name
strFile = ActiveWorkbook.FullName
''2007 / 2010 connection
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0 xml;HDR=Yes;"";"
cn.Open strCon
''ODBC Connection for sql server
scn = "[ODBC;DRIVER=SQL Server;SERVER\Instance;" _
& "Trusted_Connection=Yes;DATABASE=Test]"
sSQL = "SELECT a.Stuff, b.ID, b.AText FROM [Sheet5$] a " _
& "INNER JOIN " & scn & ".table_1 b " _
& "ON a.Stuff = b.AText"
rs.Open sSQL, cn
ActiveWorkbook.Sheets("Sheet7").Cells(1, 1).CopyFromRecordset rs
通过任何指向SQL Server的链接,您需要相当自信地使用干净的数据。
请注意,我已提到过细胞。如果您不喜欢连接工作表的想法,您还可以参考单元格和步骤,例如For i=1 To MaxRows