从Excel使用Excel中的数据使用VBA获取数据

我试图从Excel中提取数据使用一列的Excel。

我已经尝试了下面的代码,但是它没有花费太多的时间,当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 

任何帮助,我会非常感激。 谢谢!!

如果您正在寻找另一种引用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文件。