2012-07-13 90 views
2

我得到一個連續循環(我相信)。當我運行代碼時,我得到MsgBox提示符,單擊確定,程序剛剛運行並運行並永不結束?起初,我認爲這是一個連接到文件錯誤,但如果是這種情況,我應該在ADO嘗試連接到該文件時收到錯誤,對嗎? 文件不是那麼大,只有70行。我有MsgBox設置的方式,它應該提示在循環的每次迭代中單擊OK,但我永遠不會收到另一個MsgBox。建議?連續循環ADO VBA訪問2010

' 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' 
' 
' Selects 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 12.0 Macro;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 

' Write the information pulled, into the TABLE 'items_needed_table' in Access Database 
Do Until objRecordset.EOF 
    MsgBox("" & qd.Parameters("p2")) 
    Set qd = data_base.CreateQueryDef("") 
    qd.sql = "INSERT INTO items_needed_table(pr_no, line_no, desc, weeks) " & _ 
     "Values([p1],[p2],[p3],[p4])" 
    qd.Parameters("p1").Value = pr_num.Value 
    qd.Parameters("p2").Value = objRecorset.Fields.Item("line_no") 
    qd.Parameters("p3").Value = objRecordset.Fields.Item("desc") 
    qd.Parameters("p4").Value = objRecordset.Fields.Item("weeks") 
    qd.Execute 
    objRecordset.MoveNext 
Loop 

' Close Database connection 
data_base.Close 

在此先感謝您的幫助! Nathan

回答

4

擺脫錯誤恢復下一行。它幾乎不應該被使用。由於那條線,你不知道導致循環的錯誤發生在哪裏。

另一個好主意是總是在每個模塊的頂部使用Option Explicit。這將確保你總是聲明你的變量,並比任何人想象的都可以節省更多的悲傷。

+0

希望我能+2,因爲你在'On Error Resume Next'和'Option Explicit'上都有發現。 – 2012-07-13 15:54:50

+0

@你最近幾乎是我的英雄。謝謝! – nathansizemore 2012-07-13 15:58:05