Vba 无法执行字符串查询

Vba 无法执行字符串查询,vba,excel,ms-access,Vba,Excel,Ms Access,惠 我正在编写代码,以便从Excel中传输数据并将其记录在Access数据库中。我目前使用的代码是从一个站点复制的,并更改了与我的工作表相关的值和一些语句。但问题是,我无法运行我的代码,但我从其他网站获得的文件能够成功运行。你能解释一下我的代码有什么问题吗。代码如下: Sub Customer Log() Dim cn as Object Dim strQuery as string Dim custName As String Dim ordID As String Dim myDB As S

我正在编写代码,以便从Excel中传输数据并将其记录在Access数据库中。我目前使用的代码是从一个站点复制的,并更改了与我的工作表相关的值和一些语句。但问题是,我无法运行我的代码,但我从其他网站获得的文件能够成功运行。你能解释一下我的代码有什么问题吗。代码如下:

Sub Customer Log()
Dim cn as Object
Dim strQuery as string
Dim custName As String
Dim ordID As String
Dim myDB As String

'Initialize Variables
custName = Sheets("Batch_Report").Range("D4").Value
ordID = Sheets("Batch_Report").Range("D5").Value

'Database Location
myDB = "C:\Users\intern.maxvue\Dekstop\Adhariah (Intern)\Bar Code System\ReviewReport_v1_2015.accdb"
Set cn = CreateObject("ADODB.Connection")

With cn
    .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
    .ConnectionString = myDB
    .Open
End With

strQuery = "INSERT INTO CustomerLog ([CUSTOMER NAME], [ORDER ID]) " & _
           "VALUES (""" & custName & """, " & ordID & "); "

cn.Execute strQuery
cn.Close
Set cn = Nothing
End Sub
当我调试并且行到达
cn.Execute strQuery
时,“运行时错误:一个或多个必需参数没有给定值”弹出

提前感谢。

试试:

strQuery = "INSERT INTO CustomerLog ([CUSTOMER NAME], [ORDER ID]) " & _
           "VALUES ('" & custName & "', " & ordID & ")"

您是否检查了调试器中的变量custName、ordId?表CustomerLog中是否还有其他列不可为null且没有默认值?@collapsar CustomerLog表中没有其他列。顺便说一句,我发现了问题。我的ORID包含字符和数字。因此,我只需要在ORDD前后添加另一个“符号”。如果没有“符号”,它将只返回编号值。这就是参数无效的原因。无论如何,感谢您的回复:)我尝试在ORDD处添加一些引号,因为我的ORDD都是字符串,而不是编号strQuery=“INSERT INTO CustomerLog([CUSTOMER NAME],[ORDER ID])”和u”值(“&custName&”,“&ordID&”);顺便说一句,谢谢您的帮助。