2016-01-18 52 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”)值