• 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.20wincc;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的数据有效性的设定。

    先记什么多。

  • 相关阅读:
    金融数据获取的api接口
    股票实时数据接口
    【C#】通过webbrowser控件自动注册QQ号讲解
    【C#】通过webbrowser控件获取验证码
    光圈,快门, 曝光,焦距, ISO,景深。
    装修记录
    cocos2dx在win10系统上的VS2017运行时报错:丢失MSVCR110.dll
    论打击的本质(2)-视觉理论及应用篇
    论打击感的本质(1)——力的理论及应用
    android屏幕适配详解
  • 原文地址:https://www.cnblogs.com/rain64531264/p/VBA.html
Copyright © 2020-2023  润新知