我在Access中使用VBA尝试使用INSERT INTO时遇到错误,无法修复它

时间:2017-11-14 20:01:04

标签: vba ms-access

使用以下代码

  

错误3061(参数太少。预计2)

Option Compare Database

Private Sub Command0_Click()
    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet





    Set xls = New Excel.Application

    xls.Visible = True
    xls.UserControl = True

    Set wkb = xls.Workbooks.Open("link\Reliability Projects v5.xlsm", ReadOnly:=True, UpdateLinks:=False)
    Set wks = wkb.Worksheets("Projects")




    Dim RWPTitle As String 'there may be a better type to use here
    RWPTitle = wks.Range("E10").Value
    Text1.Value = RWPTitle
    Dim EstimatedCapital As Currency 'there may be a better type to use here
    EstimatedCapital = wks.Range("J10").Value
    CurrentDb.Execute "INSERT INTO Table1 (PlanTitle, EstimatedCapitalCost) Values (RWPTitle, EstimatedCapital)"








    wkb.Close False 'Close workbook.  False is so that it doesn't save


    Set wks = Nothing
    Set wkb = Nothing

    xls.Quit

    Set xls = Nothing
End Sub

*当我尝试直接使用INSERT INTO(No CurrentDb.EXECUTE)时,我得到了

  

编译错误 - 预期:语句结束

它突出显示了使用的表名。

关于为什么会发生这种情况的任何想法?

另外,我对VBA&访问。对用于处理数据库和excel文件/信息的函数/调用有什么好的参考?

2 个答案:

答案 0 :(得分:2)

我首先看到的是你的INSERT将失败,因为你使用的变量就像参数一样。 - 它应该看起来像这样,字符串用单引号,货币不是:

    CurrentDb.Execute "INSERT INTO Table1 (PlanTitle, EstimatedCapitalCost)
                      Values ('" & RWPTitle & "', " & EstimatedCapital & ")"

答案 1 :(得分:0)

以下是我喜欢在vba中处理插入的方法。然后我可以跟踪任何错误的值。

With rstTable1

  .AddNew
    !PlanTitle,  = "Text Field Here"
    !EstimatedCapitalCost = $value here
  .Update

End With