我想使用ADO從Excel文件中訪問和讀取一些內容。我知道如何打開它並執行SELECT *並將其放入Recordset對象中。我不明白的是,如果我選擇一組信息,如何訪問該Recordset中的特定字段。使用ADO VBA將Excel字段插入訪問表
代碼:
Private Sub SaveReq_Click()
'
' Saves the current entry to the database
' Into the TABLE 'pr_req_table'
'
' Open a connection to the database
dim data_base as Database
set data_base = OpenDatabase(CurrentProject.Path & "\test_database.accdb")
Sub InsertRecord()
Dim data_base As Database
Set data_base = OpenDatabase(CurrentProject.Path & "\test_database.accdb")
' Grab all information from form
' Add information to pr_req_table
Dim qd As QueryDef
Set qd = data_base.CreateQueryDef("")
qd.sql = "INSERT INTO pr_req_table(pr_no, pr_date, pr_owner, pr_link, pr_signed) " & _
"values([p1],[p2],[p3],[p4],[p5])"
qd.Parameters("p1").Value = pr_num.Value
qd.Parameters("p2").Value = Format(pr_date.Value, "mm/dd/yyyy")
qd.Parameters("p3").Value = List22.Value
qd.Parameters("p4").Value = "Excel Copy #" & elec_copy.Value
qd.Parameters("p5").Value = "Signed Copy #" & sign_copy.Value
qd.Execute
' The following section reads from the elec_copy field's hyperlink
' It scans the Excel file for items it needs to include into the table
' It enters those cells into the TABLE 'items_needed_table'
'
' Slects row by row, and if the item has been marked TRUE, inserts
' That row into the TABLE 'items_needed_table'
' Open a connection to Excel
On Error Resume Next
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & elec_copy.Value & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
' Decalre a RecordSet Object
Set objRecordSet = CreateObject("ADODB.Recordset")
' Grab all Rows in the Plain_VDR Sheet where 'needed' column == TRUE
objRecordset.Open "Select line_no, desc, weeks FROM [Plain_VDR$] Where needed = TRUE", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
' Declare a loop counter for row?
Dim x as Integer
x = 0
' Write the information pulled, into the TABLE 'items_needed_table' in Access Database
Do Until objRecordset.EOF
qd.sql = "INSERT INTO items_needed_table(pr_no, line_no, desc, weeks) " & _
"Values([p1],[p2],[p3])"
' p1 was declared earlier in code, same value as before
qd.Parameters("p2").Value = objRecorset.(ROW_X, "line_no")
qd.Parameters("p3").Value = objRecordset.(ROW_X, "desc")
qd.Parameters("p4").Value = objRecordset.(ROW_X, "weeks")
qd.Execute
x = x + 1
Loop
' Close Database connection
data_base.Close
End Sub
我關心的主要觀點是 '做,直到' 循環部分。令人懷疑的是我可以插入整個選擇,因爲'pr_no'沒有在Excel文件中定義,而是在Access數據庫中定義,因此我認爲我需要爲Excel文件中的每一行循環該命令。 我需要用什麼從記錄集對象中爲我的參數分配每行和每個字段的值?
在此先感謝您的幫助!
彌敦道
如果pr_no是自動編號,則不需要包含它。爲什麼你不是通過查詢一次插入所有數據,或者只是將範圍鏈接爲Access中的表格並運行普通的Access查詢? – Fionnuala 2012-07-11 19:58:01
pr_no不是自動編號。無法一次插入所有數據,因爲我需要爲每行分配一個pr_no。每次創建新條目時,Excel文件都會有所不同,這就是爲什麼每次輸入新條目時都需要運行它。 – nathansizemore 2012-07-11 20:16:06