|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
sub 连接服务器()
Dim cnnstr$, a% cnnstr = "provider=sqloledb;data source=PC-20180607001\SQL_express;user id=sa;password=1111111111;initial catalog=VBA_test"
Dim cnn As New ADODB.Connection
On Error Resume Next
cnn.ConnectionString = cnnstr
cnn.Open
If cnn.State <> adStateOpen Then
MsgBox "连接失败:" & Err.Description
cnn.Close: Set cnn = Nothing
Exit Sub
End If
Dim sql As String, rs As New ADODB.Recordset
sql = "SELECT DateName(day,Getdate())"
If CInt(cnn.Execute(sql)(0)) <> Day(Date) Then
MsgBox "你本机的系统时间和服务器时间不一样,请调整后再尝试!"
cnn.Close: Set cnn = Nothing
Exit Sub
End If
end sub
Sub 下载数据()
c2 = CInt(Left(UserForm4.ComboBox1.Value, 1))
Unload UserForm4
With ThisWorkbook
If c2 <> Month(Date) Or c2 <> CInt(Mid(.ActiveSheet.CommandButton3.Caption, 3, 1)) Then
Call 清空数据1
End If
.ActiveSheet.CommandButton3.Caption = Left(.ActiveSheet.CommandButton3.Caption, 2) & c2 & "月"
.Application.ScreenUpdating = False
.Application.Calculation = xlCalculationManual
End With
'---------------------------------------------设置服务器
call 连接服务器
'------------------------------------------开始下载数据
myTable = "test" & Year(Date) & "y" & c2 & "m"
With ThisWorkbook.ActiveSheet
sql = "SELECT * from " & myTable
rs.Open sql, cnn, adOpenKeyset, adLockOptimistic '-----------------这句就出问题
end with
end sub
问题:
1、因为有多个过程都需要连接SQL服务器,所以想把连接SQL的代码单独写一个过程;然后用其它过程去调用(call 连接服务器)。
2、没有用代码关闭SQL连接,但是过程结束后,连接自然就断了,后面的代码要用到连接,就报错(就是红色的那句)。
3、请教高手怎么破。
|
|