簡體   English   中英

使用Excel中的數據使用vba從Access獲取數據

[英]getting data from Access using vba using data from excel

我正在嘗試使用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

任何幫助我將不勝感激。 謝謝!!

如果您正在尋找引用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文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM