使用Excel“插入”语句出现语法错误

时间:2013-12-02 05:35:27

标签: excel vba excel-vba

执行“插入”声明

时遇到问题

我尝试在Excel VB中运行:

insertQ = "INSERT INTO [Sheet1$] (Stockgroup, Stockcode, transdate, LastUpdate, time) VALUES ('990000', 'birthday', '21/12/2101', '','" & Time & "')"

但它显示语法错误。

如果我取出最后两个字段

,它会起作用
insertQ = "INSERT INTO [Sheet1$] (Stockgroup, Stockcode, transdate) VALUES ('990000', 'birthday', '21/12/2101')"
你以前遇到过这种情况吗? @@

1 个答案:

答案 0 :(得分:0)

这对我有用:

Sub sof20321516Insert2Excel()

  Dim strSQL
  Dim cnn, rst

  On Error GoTo ErrHandler

  Set cnn = CreateObject("ADODB.Connection")
  cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0" _
    & ";Data Source=" & ThisWorkbook.FullName _
    & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;HDR=YES"""
  cnn.Open
'
  strSQL = "INSERT INTO [Sheet1$] (Stockgroup, Stockcode, transdate, LastUpdate, `time`) VALUES ('990000', 'birthday', '21/12/2101', '','" & Time & "')"
  Set rst = cnn.Execute(strSQL)

'
' close ADO objects:
'
' rst.Close
  Set rst = Nothing

  cnn.Close
  Set cnn = Nothing

  Exit Sub
ErrHandler:
  MsgBox Err.Description
  Set cnn = Nothing

End Sub

使用ADO,字段名称time应该是反引号。与注释一样,关键字时间不能用作SQL字符串中的裸字段名称。