如何在EXCEL中运行SQL查询
展开全部
Sub Test()
'工具->引用->Microsoft ActiveX DataObjects 2.0
'定义连接对象
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
'连接字符串
strcn = "Driver=sql server;Server=服务器;database=数据库;uid=sa;pwd=密码"
cnn.Open strcn
Dim D1 As Date '开始日期
Dim D2 As Date '结束日期
D1 = Range("B2").Text
D2 = Range("B3").Text
If IsDate(D1) And IsDate(D2) Then
rs.Open "sp_djcount '" & D1 & "','" & D2 & "'", strcn, 3, 1 '存储过程
rs.Open "Select * From 表 ", strcn, 3, 1 'sql语句
Range("A5").CopyFromRecordset rs
MsgBox "成功!!!", vbInformation + vbOKOnly, "温馨提示"
Else
MsgBox "请输入开始日期和截止日期", vbQuestion + vbOKOnly, "温馨提示"
End If
'关闭连接
cnn.Close
Set rs = Nothing
Set cnn = Nothing
End Sub
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询