zoukankan      html  css  js  c++  java
  • 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的数据有效性的设定。

    先记什么多。

  • 相关阅读:
    Flink Table环境配置、读取外部数据(File、Kafka)以及查询转换
    Flink之Table初探
    Flink之Watermarks
    Flink之ProcessFunction侧输出流
    Flink之ProcessFunction案例
    Flink之Mysql数据CDC
    Express ejs 模板做的 app.js 文件
    金额转换文章(100=>零佰)
    将 音频流(MP3流)并进行播放
    浅谈MySQL(一):存储引擎与索引
  • 原文地址:https://www.cnblogs.com/rain64531264/p/VBA.html
Copyright © 2011-2022 走看看