帮我优化以下代码,每10000行导出至新EXECL表直至数据记录导完: Dim db As DAO.Database Dim rs As DAO.Recordset Dim strSQL As String Dim strFileName As String Dim i As Long '设置导出文件路径和文件名 strFileName = "C:\Users\icd\Desktop\流水分割" Set db = CurrentDb() strSQL = "SELECT 导出数据.* FROM 导出数据" Set rs = db.OpenRecordset(strSQL, dbOpenSnapshot) '每10000条记录导出到一个新的文件 Do While Not rs.EOF If i Mod 10000 = 0 Then If i <> 0 Then DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "ExportData", strFileName & Format(i, "000000") & ".xlsx", True End If rs.Close Set rs = db.OpenRecordset("导出数据", dbOpenSnapshot) End If i = i + 1 rs.MoveNext Loop '导出最后一份文件 If i Mod 10000 <> 0 Then DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "导出数据", strFileName & Format(i - (i Mod 10000), "000000") & ".xlsx", True End If rs.Close Set rs = Nothing Set db = Nothing
时间: 2024-02-14 16:12:08 浏览: 97
可以尝试使用ADO来优化代码,ADO可以更快地处理大量数据。以下是优化后的代码:
```
Dim adoConn As New ADODB.Connection
Dim adoRS As New ADODB.Recordset
Dim strSQL As String
Dim strFileName As String
Dim i As Long
Dim rowCount As Long
'设置导出文件路径和文件名
strFileName = "C:\Users\icd\Desktop\流水分割\"
'连接数据库
adoConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurrentDb.Name
'查询数据记录数
strSQL = "SELECT COUNT(*) FROM 导出数据"
Set adoRS = adoConn.Execute(strSQL)
rowCount = adoRS.Fields(0).Value
adoRS.Close
'每10000条记录导出到一个新的文件
i = 0
Do While i < rowCount
strSQL = "SELECT TOP 10000 * FROM 导出数据 WHERE ID > " & i & " ORDER BY ID"
adoRS.Open strSQL, adoConn, adOpenStatic, adLockReadOnly
If Not adoRS.EOF Then
'导出到Excel文件
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "ExportData", strFileName & Format(i, "000000") & ".xlsx", True
End If
i = i + 10000
adoRS.Close
Loop
'关闭连接
adoConn.Close
Set adoRS = Nothing
Set adoConn = Nothing
```
优化后的代码使用ADO连接到数据库,查询数据记录数,并使用TOP和ORDER BY语句每次查询10000条记录。同时,将rs对象改为adoRS对象,使用ADO特有的方法来操作记录集。这样可以更快地处理大量数据,并且可以避免使用DAO时出现的内存溢出问题。
阅读全文