【问题标题】:I am getting errors trying to use INSERT INTO using VBA in Access, and can't fix it尝试在 Access 中使用 VBA 使用 INSERT INTO 时遇到错误,无法修复
【发布时间】:2017-11-17 00:41:00
【问题描述】:

我得到以下代码

错误 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 和 Access 非常陌生。用于处理数据库和 excel 文件/信息的函数/调用有什么好的参考吗?

【问题讨论】:

    标签: vba ms-access


    【解决方案1】:

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

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

    【讨论】:

    • 对于插入,我需要列出表中第一个括号内的每个字段,然后是每个字段的值(或“”不输入任何内容),或者我可以只列出我有值的字段,然后是这些值?
    • 您不需要包含所有字段,只需包含架构所需的字段即可。
    • @J.Ryan -- 如果此答案满足您的需求,请将其标记为正确/已接受。这将有助于将来可能遇到类似问题的其他人,因为他们会将问题视为可接受的解决方案
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 2023-03-04
      相关资源
      最近更新 更多