【发布时间】:2021-01-20 22:41:23
【问题描述】:
我在一个 Excel 文件和两台相同的笔记本电脑上有一个 vba 项目。
两台笔记本电脑上的office安装都是64位的。
在第一台笔记本电脑上,执行以下代码需要 20 秒,而在第二台笔记本电脑上则需要很长时间。
我搜索了很多,但没有找到导致问题的原因。
欢迎提出任何建议。
代码是
Sub GetDataFromADO()
On Error GoTo ErrorHandler
'Turn of Automatic calculation'
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculateManual
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilterMode = False
Worksheets("Data").Rows(8 & ":" & Worksheets("Data").Rows.Count).Delete
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=Server;Initial Catalog=Database;User ID=user;Password=pass;"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from table where date>= DATEADD(yy,DATEDIFF(yy,0,GETDATE())-1,0) order by column1, column2"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A8").CopyFromRecordset (objMyRecordset)
'Create Index for lookups'
'Find Last Row'
Dim Lastrow As Long
Lastrow = Range("A" & Rows.Count).End(xlUp).Row
'Copy Formula Until the last row'
Range("AG8:AG" & Lastrow).Formula = "=E8&F8"
ErrorHandler:
'Turn on Automatic calculation'
Application.Calculation = xlAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
【问题讨论】:
-
尝试在使用后关闭您的记录集和连接 - 这也应该是您的默认错误处理程序。你永远不希望外围连接挂起(减慢速度)..