VBA在SQL中将具有多列的Update语句插入表中

时间:2017-06-21 03:46:00

标签: sql-server excel vba

任何人都可以帮助我在哪里做错了..我正在构建一个包含多列的更新语句,以使用VBA和Excel中的值更新MSQL。继承了我的简单代码,我在函数中解析变量以执行SQL命令(我有一个表名" People"我已经定义了所有列):

    Function GetUpdateTextSQL(PIC As String, 
          Customer As String, 
          DOB As Date, 
          Rank As String, 
          Organization As String,
          Status As String, 
          Gender As String, 
          Religion As String, 
          Hobby As String,
          CreatedBy1 As String, 
          CreatedOn1 As Date, 
          ChangedBy1 As String,
          ChangedOn1 As Date,
          PeopleID As Integer) As String

     SQLStr = _
          "UPDATE People" & _
          "SET PIC = " & _
          "'" & PIC & "', Customer = '" & Customer & "'," & _
          "DOB = '" & Format(DOB, "yyyy-mm-dd") & "', Rank = '" & Rank & "'," & _
          "Organization = '" & Organization & "',Status = '" & Status & "', Gender = '" & Gender & "'," & _
          "Religion = '" & Religion & "', Hobby = '" & Hobby & "'," & _
          "CreatedBy = '" & CreatedBy1 & "', CreatedOn = '" & CreatedOn1 & "'," & _
         "ChangedBy = '" & ChangedBy1 & "', ChangedOn = '" & ChangedOn1 & "'" & _
        "WHERE PeopleID =  & PeopleID &;"

    GetUpdateTextSQL = SQLStr

//在这里我插入并执行以下命令以从excel获取值:

For Each r In Range("A45", Range("A45").End(xlDown))

    CmdForSave.CommandText = _
        GetUpdateTextSQL( _
            r.Offset(0, 1).Value, r.Offset(0, 2).Value, _
            r.Offset(0, 3).Value, _
            r.Offset(0, 4).Value, r.Offset(0, 5).Value, _
            r.Offset(0, 6).Value, r.Offset(0, 7).Value, _
            r.Offset(0, 8).Value, r.Offset(0, 9).Value, _
            r.Offset(0, 10).Value, r.Offset(0, 11).Value, _
            r.Offset(0, 12).Value, r.Offset(0, 13).Value, _
            r.Offset(0, 0).Value)
        CmdForSave.Execute
Next r

我得到的错误是' PIC'附近的语法不正确 我的代码出了什么问题?我使用MS SQL Express(SQL 2012)

1 个答案:

答案 0 :(得分:0)

全部谢谢,

我已经弄明白为什么问题与更新SQL语句的空间有关。

使用VBA的正确语句(SET之前的空格,WHERE之前的空格):

SQLStr = _
    "UPDATE People" & _
    " SET PIC = '" & PIC & "', Customer = '" & Customer & "'" & _
    " WHERE PeopleID = '" & PeopleID & "';"