【发布时间】:2019-03-28 20:39:48
【问题描述】:
我正在运行下面的代码,将 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
【问题讨论】:
-
而不是
While Not rs.EOF和Wend之间的所有内容。 -
实际上,而不是整个
While...Wend块。 FWIWWhile...Wend是一个过时的构造,应该是Do While...Loop以允许Exit Do语句。 -
你需要以某种方式点击索引......尝试
WHERE Id <> 0(假设是单列,自动编号PK) -
试试看。假设员工是一个文本字段:
WHERE ID <> 0 AND employee ='" & sheet3.range("D5") & "'"