VBA访问SQLSERVER2005筛选数据库
EXCEL版本2010,
引用
Private Sub CommandButton1_Click() Dim conn As New ADODB.Connection Dim rs As New ADODB.Recordset Set Cnn = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") Dim connstr Dim sql Dim bt Dim et Dim bno Dim sht As Worksheet connstr = "Provider=sqloledb;Server=172.16.10.20\wincc;Database=KMTC;Uid=sa;Pwd=0000;" 'This Connection String must be remembered for a long period. conn.Open connstr bt = Range("B1").Value et = Range("D1").Value bno = Range("G1").Value sql = "SELECT '" & bt & "到" & et & "' as savedate ,[Materials_Name]" & vbNewLine & _ " ,sum([Save_Weight]) as settedWeight" & vbNewLine & _ " ,sum([PV_Weight]) as realWeight" & vbNewLine & _ " FROM [KMTC].[dbo].[Save_Weight]" & vbNewLine & _ "where save_date between '" & bt & "' and '" & et & "'" If bno <> Empty Then sql = sql & " and [Batch_Number] = '" & bno & "'" End If sql = sql & "group by [Materials_Name]" rs.Open sql, conn i = 4 Set sht = ThisWorkbook.Worksheets("sheet3") For j = 4 To 30 sht.Cells(j, 1) = Empty sht.Cells(j, 2) = Empty sht.Cells(j, 3) = Empty sht.Cells(j, 4) = Empty sht.Cells(j, 8) = Empty sht.Cells(j, 9) = Empty sht.Cells(j, 10) = Empty Next Do While Not rs.EOF sht.Cells(i, 1) = rs("savedate") sht.Cells(i, 2) = rs("Materials_Name") sht.Cells(i, 3) = rs("settedWeight") sht.Cells(i, 4) = rs("realWeight") rs.MoveNext i = i + 1 Loop rs.Close sql = "SELECT [Batch_Number]" & vbNewLine & _ " ,sum([Save_Weight]) as settedWeight" & vbNewLine & _ " ,sum([PV_Weight]) as realWeight" & vbNewLine & _ " FROM [KMTC].[dbo].[Save_Weight]" & vbNewLine & _ "where save_date between '" & bt & "' and '" & et & "'" & vbNewLine & _ "group by [Batch_Number]" rs.Open sql, conn i = 4 Do While Not rs.EOF sht.Cells(i, 8) = rs("Batch_Number") sht.Cells(i, 9) = rs("settedWeight") sht.Cells(i, 10) = rs("realWeight") rs.MoveNext i = i + 1 Loop rs.Close conn.Close End Sub
好吧,还有一些excel的数据有效性的设定。
先记什么多。