尝试从Excel更新Access表中的记录

时间:2017-09-19 14:23:21

标签: excel excel-vba vba

我认为我的VBA应该与你在下面看到的一样,但它不起作用。我收到一条错误消息,内容为:“没有给出一个或多个必需参数的值。”

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

对可能出错的任何想法?这应该非常接近!!

1 个答案:

答案 0 :(得分: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