我正在尝试使用excel列从Access中提取数据。
我尝试了以下代码,但是当excel中的行数超过5k行时,它不会占用太多时间。有没有人知道引用excel数据以获得结果的更好方法:
Sub ddd()
Const dbloc As String = "C:\Users\mysystem\Downloads\Database11.accdb"
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim xlbook As Workbook
Dim xlsheet As Worksheet
Dim a As Long
Dim SQL As String
Set xlbook = ActiveWorkbook
Set xlsheet = xlbook.Worksheets(1)
xlsheet.Range("B2:Z100000").ClearContents
Set db = OpenDatabase(dbloc)
SQL = "SELECT Material, MPN "
SQL = SQL & "FROM Sheet2 "
SQL = SQL & "WHERE Material IN ("
Dim r As Range
For Each r In Range("A2:A19098")
SQL = SQL & r.Text & ","
Next r
SQL = Left(SQL, Len(SQL) - 1) 'Drop last comma
SQL = SQL & ")"
' i want to change this for loop because my range might vary from 80-100k
rows and this method is not working. i got a suggestion here that i can
use a table for this. But i am new to macros and access and not sure of
the syntax. Can anyone please help with the syntax. Assuming tablename for
the excel data is column1 and ranges from a2:a100000
Set rs = db.OpenRecordset(SQL)
', dbOpenSnapshot)
If rs.RecordCount = 0 Then
MsgBox "No data retrieved from database", vbInformation + vbOKOnly, "No
Data"
GoTo SubExit
Else
rs.MoveLast
recCount = rs.RecordCount
rs.MoveFirst
End If
xlsheet.Range("C2").CopyFromRecordset rs
End Sub
任何帮助都会让我非常感激。谢谢!
答案 0 :(得分:1)
如果您正在寻找引用Excel列的替代方法,可以使用以下方法:
SQL = "SELECT Material, MPN "
SQL = SQL & "FROM Sheet2 "
SQL = SQL & "WHERE Material IN ("
SQL = SQL & "SELECT * FROM [A1:A19098] IN '"
SQL = SQL & ActiveWorkbook.FullName & "'"
SQL = SQL & " 'Excel 12.0 Macro;')"
这允许DAO数据库引擎通过OleDb直接查询您的Excel文件,而不是将每一行作为文本传递,这应该更有效。
在执行此操作之前应保存Excel文件(并且最好从其他文件触发它,但在从同一文件触发时对我有用)。
请注意,我故意包含1行,因为第一行在使用时包含列名。
我假设您正在使用.xlsm
文件。