2016-01-18 165 views
0

我想在Excel 2010中更新4個單元格到我的MS Access 2010使用VBA下面的代碼。問題是,有時它會更新表記錄中的那些字段,而其他時間則不會。我想知道是否有人可以在我的代碼上發現導致不一致的原因。使用Excel vba更新MS Access記錄與記錄Id


'Add a reference to the Microsoft ActiveX Data 2.8 or later Object Library 
'via the Tool | References... in the VB-editor 
Dim cnt As ADODB.Connection 
Dim rst As ADODB.Recordset 
Dim stDB As String 
Dim stCon As String 

'Instantiate the ADO COM's objects. 
Set cnt = New ADODB.Connection 
Set rst = New ADODB.Recordset 

'Pathway and name of the database 

stDB = "P:\Quote Log.mdb" 
'Create the connectionstring. 
stCon = "Provider=Microsoft.Ace.OLEDB.12.0; Persist Security Info = False;" & _ 
"Data Source=" & stDB & ";" 

'Open the connection 
cnt.Open stCon 

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
'Find and Update the record in Access 
With rst 
    .Index = "PrimaryKey" 
    .CursorLocation = adUseServer 
    .Open "tbQuote", cnt, 1, 3, adCmdTableDirect 
    .Seek Range("dx32").Value 
    If Not rst.EOF Then 
    .Fields("QuoteNum") = Sheets("Quote Notice").Range("dx32").Value 

     .Fields("OtherCost") = Sheets("Cost").Range("b3").Value 
     .Fields("StocklistCost") = Sheets("Cost").Range("b4").Value 
     .Fields("DesignHrs") = Sheets("Cost").Range("b5").Value 
     .Fields("ProductionHrs") = Sheets("Cost").Range("b6").Value 

    .Update 

    Else 
    MsgBox "No such record...not updating." 
    End If 
End With 
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 

'Close the recordset and close the connection. 
rst.Close 
cnt.Close 

Set cnt = Nothing 

ExitSub: 
Set rs = Nothing 
'...and set to nothing if no such record 
Exit Sub 

謝謝你,

hughv

+0

考慮您的環境。當它不起作用時,工作簿是否擁有它試圖更新的那個數據庫記錄的獨佔寫訪問權限?其他用戶或應用程序是否同時連接到.mdb文件?使用互聯網文件夾(Dropbox,Google Drive,OneDrive)或拇指驅動器可能會導致不一致。 – Parfait

回答

0

好了,發現我的問題......這行需要正確地引用到表和單元格。 .Seek範圍( 「dx32」)值

到:。 .seek工作表( 「報價通知」)的範圍( 「dx32」)值