[英]VBA obtaining a SUM of values from MS Access, returns error: No Value Given For One or More Parameter
I have the following code to retrieve a sum out of an access field. 我有以下代码来检索访问字段中的总和。 keep getting the error "No Value Given For One or More Parameter".
不断收到错误“没有为一个或多个参数赋值”。 I'm assuming its something simple.
我假设它很简单。 I tried looking up the syntax and google appears to give me what i already have.
我尝试查找语法,谷歌似乎给了我我已经拥有的东西。 Appreciate your help.
感谢您的帮助。
EDIT 编辑
Public Sub sum()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim countfrmdb As String
Dim currentmth As String
currentmth = Sheets("Data").Range("f3") 'this has been formatted to get the month name. e.g: Jan. Thats how its in my database.
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=data.mdb"
strSql = "SELECT SUM(field_name) As Total FROM Table_name WHERE field_month_name = " & currentmth
cn.Open strConnection
Set rs = cn.Execute(strSql)
countfrmdb = rs.Fields(0)
MsgBox (countfrmdb)
You indicated currentmth is a text value containing the current month. 您指示currentmth是包含当前月份的文本值。 So when you add currentmth to the
WHERE
clause without enclosing it in quotes, the db engine thinks Jan is the name of a parameter instead of a text value. 因此,当将currentmth添加到
WHERE
子句而不用引号引起来时,数据库引擎会认为Jan是参数的名称而不是文本值。
Change this ... 改变这个...
WHERE field_month_name = " & currentmth
to this ... 为此...
WHERE field_month_name = '" & currentmth & "'"
A good way to troubleshoot these type of issues is to examine the actual text of the SQL statement you're asking Access to execute. 解决这类问题的一种好方法是检查您要求Access执行的SQL语句的实际文本。
Debug.Print
is useful for that purpose. Debug.Print
对于此目的很有用。
strSql = "SELECT SUM(field_name) As Total FROM Table_name WHERE field_month_name = " & currentmth
Debug.Print strSql
You can then view the output from Debug.Print
in the Immediate window. 然后,您可以在“即时”窗口中查看
Debug.Print
的输出。 And you can copy the statement text from there and paste it into SQL View of a new Access query for testing. 您可以从此处复制语句文本,然后将其粘贴到新的Access查询的SQL视图中进行测试。 Or you can show us the actual statement text which is producing the error your reported.
或者,您可以向我们显示产生您报告的错误的实际语句文本。
Based off of the information found here: No value given for the required parameter I would say that your Field_Name or table_name aren't correctly spelled. 根据在此找到的信息: 没有为必需的参数提供值我要说的是您的Field_Name或table_name的拼写不正确。 You can test this by purposefully putting in the wrong field name and you will get the same error you are getting.
您可以通过有意地输入错误的字段名称来进行测试,并且会遇到相同的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.