|
- Sub Test()
- Dim intYear As Integer, intMonth As Integer
-
- intYear = Sheet7.Range("L2").Value
- intMonth = Sheet7.Range("M2").Value
-
- SelectIDByYearMonth intYear, intMonth
- End Sub
- Function SelectIDByYearMonth(intYear As Integer, intMonth As Integer)
- Dim Conn As Object, Rst As Object, strPath As String
- Dim strConn As String, strSQL As String
-
- Set Conn = CreateObject("ADODB.Connection")
- Set Rst = CreateObject("ADODB.Recordset")
- strPath = ThisWorkbook.FullName '设置工作簿的完整路径和名称
- Select Case Application.Version * 1 '设置连接字符串,根据版本创建连接
- Case Is <= 11
- strConn = "Provider=Microsoft.Jet.Oledb.4.0;Extended Properties=excel 8.0;Data source=" & strPath
- Case Is >= 12
- strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strPath & ";Extended Properties=""Excel 12.0;HDR=YES"";"""
- End Select
- Conn.Open strConn '打开数据库链接
- strSQL = "SELECT 单号 " & _
- "FROM [数据库$A1:K12] " & _
- "WHERE Year(录单日期) = " & intYear & " And Month(录单日期) = " & intMonth & " " & _
- "Group By 单号"
- Rst.Open strSQL, Conn, 3, 1 '执行查询,并将结果输出到记录集对象
- ActiveSheet.Range("P1").CopyFromRecordset Rst
- Set Rst = Nothing
- Set Conn = Nothing
- End Function
复制代码 |
|