|
- Option Explicit
- Sub SqlQuery()
- Dim conn As Object, rst As Object, strSQL$, i&, PathStr$, sht As Worksheet
- If VBA.IsDate([c3]) And Len([d3]) > 0 Then
- Set conn = CreateObject("ADODB.Connection")
- Set rst = CreateObject("ADODB.Recordset")
- PathStr = ThisWorkbook.FullName
- Set sht = Sheet2
- Dim rData As Range: Set rData = sht.Range("B7:G" & sht.Cells(sht.Rows.Count, 2).End(xlUp).Row)
- Select Case Application.Version * 1
- Case Is <= 11
- conn.Open "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" & PathStr & ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=0'"
- Case Is >= 12
- conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathStr & ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=0'"
- End Select
- strSQL = "SELECT DISTINCT 品名 FROM [原料出入明细$" & rData.Address(0, 0) _
- & "] WHERE 日期=#" & [c3].Text & "# AND 出入类型='" & [d3] & "'"
- rst.Open strSQL, conn, 1, 1
- With Sheet3
- Dim lastR As Long: lastR = .Cells(.Rows.Count, 3).End(xlUp).Row
- If lastR > 5 Then .Range("C5:C" & lastR).ClearContents
- .Range("c5").CopyFromRecordset rst
- End With
- rst.Close: conn.Close: Set conn = Nothing: Set rst = Nothing
- End If
- End Sub
复制代码 |
|