2017-09-19 66 views
1

我认为我的VBA应该与您在下面看到的内容类似,但它不起作用。我收到一条错误消息:“没有给出一个或多个必需参数的值。”试图从Excel更新访问表中的记录

Sub Execute_UpdateQuery() 
    Dim NumOfRec As Integer 
    Dim strPath As String 
    Dim rCell As Range 
    Dim rRng As Range 
    Dim sht As Worksheet 
    Dim LastRow As Long 

    DBFullName = ThisWorkbook.Path & "\Stakeholder.accdb" 

    Set cn = CreateObject("ADODB.Connection") 
    cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBFullName & ";" 

NumOfRec = 0 
Dim i As Integer, j As Integer 

With Worksheets("Temp") 
Set sht = ThisWorkbook.Worksheets("Temp") 
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 

i = 11 
    Set rRng = Sheet1.Range("A11:A" & LastRow) 
    For Each rCell In rRng.Cells 
     For j = 2 To 8 
     Debug.Print .Cells(i, j).Value 
      TheUpdate = .Cells(10, j).Value 
      cn.Execute "UPDATE ALLL_HISTORY SET " & TheUpdate & " = '" & .Cells(i, j).Value & _ 
        "' WHERE DESC1 = " & "'" & .Cells(i, 1).Value & "'", , adExecuteNoRecords 
      NumOfRec = NumOfRec + 1 
     Next j 
    i = i + 1 
    Next rCell 
End With 

MsgBox (NumOfRec & " records were updated.") 
cn.Close 
Set conn = Nothing 
End Sub 

这些图片可能会有所帮助。

enter image description here

enter image description here

什么可能是错有什么想法?这应该是非常接近!

+0

什么行会抛出错误? – BruceWayne

+2

'DESC1'字段显示为文本。尝试在单引号中包装更新值。 'WHERE DESC1 ='“&.Cells(i,1).Value&”'“'。您可能还需要在'SET'语法中进行操作,Access对此需要使用文本类型的列 –

+2

不知道什么列类型您有'LLR_Product',但试试这个:'cn.Execute“UPDATE ALLL_HISTORY SET”&TheUpdate&“='”&.Cells(i,j).Value&“'WHERE DESC1 =”&.Cells(i ,1).Value,NumOfRec,adExecuteNoRecords' – Zac

回答

3

当您将3-SYN传递给SQL时,它会尝试将其解析为numeric value 3 minus value of SYN - 由于SYN不是列名,因此推测为参数。

该错误表明它无法找到该参数。使用引号括起来的值告诉SQL它是文本并且应该解决你的问题。

cn.Execute "UPDATE ALLL_HISTORY SET " & TheUpdate & " = '" & .Cells(i, j).Value & _ 
     "' WHERE DESC1 = " & .Cells(i, 1).Value, NumOfRec, adExecuteNoRecords 
+0

没错,谢谢大家! – ryguy72