我正在运行以下代码,以将Access数据库中的数据检索到Excel中。该代码大约需要1分钟才能执行。当前大约有8列的500条记录。我可以做些什么来修改我的代码以使其运行得更快?
Sub sync_Data()
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim mysqlSt As String
Dim rowindex As Long
mysqlSt = "SELECT pbsclients.client, pbsclients.priority, pbsclients.source, pbsclients.lastcontact, pbsclients.result, pbsclients.nextsteps, pbsclients.attempts, pbsclients.notes FROM pbsclients; "
Set cn = New ADODB.Connection
With cn
.ConnectionString = con1
.Open
End With
rowindex = 2
Set rs = New ADODB.Recordset
rs.Open mysqlSt, cn, adOpenDynamic, adLockOptimistic
While Not rs.EOF
Sheet3.Cells(rowindex, 1) = rs!client
Sheet3.Cells(rowindex, 2) = rs!Priority
Sheet3.Cells(rowindex, 3) = rs!Source
Sheet3.Cells(rowindex, 4) = rs!lastcontact
Sheet3.Cells(rowindex, 5) = rs!result
Sheet3.Cells(rowindex, 6) = rs!nextsteps
Sheet3.Cells(rowindex, 7) = rs!attempts
Sheet3.Cells(rowindex, 8) = rs!Notes
rowindex = rowindex + 1
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
Exit Sub
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
最佳答案
这是我的代码的工作版本,运行和检索大约需要2秒,而上面的代码需要45秒-1分钟。
Sub sync_Data()
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim mysqlSt As String
Dim rowindex As Long
mysqlSt = "SELECT pbsclients.client, pbsclients.priority, pbsclients.source, pbsclients.lastcontact, pbsclients.result, pbsclients.nextsteps, pbsclients.attempts, pbsclients.notes FROM pbsclients WHERE Id <> 0 AND pbsclients.branch = '" & Sheet3.Range("Z1") & "'"
Set cn = New ADODB.Connection
With cn
.ConnectionString = con1
.Open
End With
rowindex = 2
Set rs = New ADODB.Recordset
rs.Open mysqlSt, cn, adOpenDynamic, adLockOptimistic
Do While Not rs.EOF
Sheet3.Range("A2").CopyFromRecordset rs
Loop
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Exit Sub
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
关于mysql - 如何加速ADODB连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55406495/