|
楼主 |
发表于 2012-3-1 19:53
|
显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
'方法1
Sub ConnectSQL()
Dim StartTime
StartTime = Timer
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim rsString As String
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.ConnectionString = "Driver={sql server};server=peksapp04;uid=;pwd=;database=sanofi pasteur production;AutoTranslate=False"
conn.Open
rsString = "select No_ as Code,Name as Name_cn, [name 2] as Name_en from [Sanofi Pasteur$Vendor] where No_ like 'V-%' order by No_"
rs.Open rsString, conn, 1, adLockReadOnly
If rs.RecordCount > 0 Then
'复制字段名
For i = 1 To rs.Fields.Count
Cells(1, i) = rs.Fields(i - 1).Name
Next i
'复制全部数据
Range("A2").CopyFromRecordset rs
'设置工作表格式
End If
'关闭记录集及数据库连接,并释放变量
rs.Close
conn.Close
Set rs = Nothing
Set cnn = Nothing
MsgBox Timer - StartTime
End Sub
'方法2
Sub ConnectSQL2()'用此方法连接数据库前先需在在本机进行DSN数据源设置 此处设为"na”
Dim StartTime
StartTime = Timer
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim rsString As String
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.ConnectionString = "DSN=na;uid=;pwd=;database=sanofi pasteur production;autotranslate=false"
conn.Open
rsString = "select No_ as Code,Name as Name_cn, [name 2] as Name_en from [Sanofi Pasteur$Vendor] where No_ like 'V-%' order by No_"
rs.Open rsString, conn, 3, adLockReadOnly
If rs.RecordCount > 0 Then
'复制字段名
For i = 1 To rs.Fields.Count
Cells(1, i) = rs.Fields(i - 1).Name
Next i
'复制全部数据
Range("A2").CopyFromRecordset rs
'设置工作表格式
End If
'关闭记录集及数据库连接,并释放变量
rs.Close
conn.Close
Set rs = Nothing
Set cnn = Nothing
MsgBox Timer - StartTime
End Sub
'方法3
Sub ConnectSQL3() '用此方法连接数据库前先需在在本机进行DSN数据源设置,然后在EXCEL中导入外部数据,选择设置好的数据源,然后进入MS QUERY中设置要返回的字段及条件。
StartTime = Timer
Dim rng As Range
Set rng = Sheet4.Range("a4")
rng.QueryTable.Refresh BackgroundQuery:=False
Set rng = Nothing
MsgBox Timer - StartTime
End Sub
'方法4
将方法1分拆二部分,先建立连接,再返回数据,将二次的时间相加得到总的返回数据时间
|
|