I am getting "No value given for one or more required parameters" - vba

I am getting
No value given for one or more required parameters
I am new in Excel VBA. What is wrong with the query? Below is the code I am using to get the value from a access data based and I want to search database using Name ID.

If nameID is a string then you should use the line below:
MyQuery = "SELECT * FROM ContDb WHERE NameID = '" & Val(Me.TxtBox1.Value) & "'"
But since you're using the Val-function, NameID might be an integer and then you should use:
MyQuery = "SELECT * FROM ContDb WHERE NameID =" Val(Me.TxtBox1.Value)

Related

Passing a string variable in SQL query

I am trying to write a SQL query that takes in WHERE conditional value from a variable.
The variable is a string type and it is being extracted first from a different table using a different query through the use of recordsets. I think I got the quotations right in the query but it shows "Undefined function 'rsDB' in expression" error.
extPMBActID_SQL = "SELECT * FROM PMB;"
Set rsDB = CurrentDb.OpenRecordset(extPMBActID_SQL, dbOpenDynaset)
testID = Left(rsDB.Fields("ActivityID"), 2)
instRptGen_SQL = "SELECT AreaName FROM Area WHERE AreaID =" & "Left(rsDB.Fields('ActivityID'), 2)" & ";"
Set rsDB = CurrentDb.OpenRecordset(instRptGen_SQL, dbOpenDynaset)
I think whenever the query is ran, it is somehow not able to fetch rsDB.Fields("ActivityID") value. I am sure that testID variable does have the value.
Any ideas what I am missing here?
Remove the quotes from that second part:
instRptGen_SQL = "SELECT AreaName FROM Area WHERE AreaID =" & _
Left(rsDB.Fields("ActivityID").Value, 2)
You don't need the terminating ;, and if AreaID is not numeric you need single quotes around the value:
instRptGen_SQL = "SELECT AreaName FROM Area WHERE AreaID ='" & _
Left(rsDB.Fields("ActivityID").Value, 2) & "'"

Vb 2015 query with parameters not working

I already used parametrized queries with no problem, but today I'm stuck on an error that I cannot debug.
This is my working query
cmd.CommandText = "select idcliente, ragsociale from Clienti where idcliente =" & strName & " or codiceamministrazione='" & strName & "' or piva='" & strName & "' or codfisc='" & strName & "'"
The same, but with parameter, not working
cmd.CommandText = "select idcliente, ragsociale from Clienti where idcliente = #Cliente or codiceamministrazione=#Cliente or piva=#Cliente or codfisc=#Cliente"
cmd.Parameters.AddWithValue("#Cliente", strName)
I use this in an autocomplete procedure that shows the name of a client based on internal id or on commercial license number (and other similar codes). On the db a client record can have all the code fields compiled or just 1.
With the non-parametrized query the autocomplete suggestion pop-up,with the parametrized one nothing shows. No errors either.
EDIT:
using this
cmd.Parameters.Add("#Cliente", SqlDbType.VarChar)
cmd.Parameters("#Cliente").Value = strName
now another query (omitted before for semplicity) in the same function works, but, strange enough, the one for what I did this question don't.
Working:
cmd.CommandText = "select idcliente, ragsociale from Clienti where ragsociale like '%'+#Cliente+'%' or codiceamministrazione=#Cliente"
Still not Working:
cmd.CommandText = "select idcliente, ragsociale from Clienti where idcliente = #Cliente or piva=#Cliente or codfisc=#Cliente"
In your original query, when testing against idcliente, you treat strName as a number (no quotes round it), but for all the other fields you treat it like a string. So you're implying it could potentially contain a number or a string. This is problematic, if you type a number, and the parameterised version of the query now treats it like a string in all cases, then it won't match the numeric value of idcliente in the DB and therefore you may get no results.
To clarify: if your input is a number, but your query thinks it's a string (because of the data type in the param), it will not match against any numeric field in the database. 12345 != "12345".
You need to define separate parameters for these scenarios. You can pass the same value into them, but in one case set the parameter's datatype to varchar and in the other case to int (you might need to check if the value can be parsed as a number before you do this, otherwise it will likely crash. In that case just set it null or 0 or something that won't make an accidental match).

Create Variable or Method to use value in multiple forms

Fairly new to VBA. I have a list box on a form within Access which is populated with data from a table. Selecting a value from the list box gives and ID which is then used to perform a query. I need this ID to be available for use in another form to perform a query based on the Value. What is the best way of achieving this?
`Dim IDValue As String
IDValue = Me.lstBoxCompanyName.Value
CompDetailSQL = "SELECT * FROM Companies WHERE Companies.CompanyID = " & IDValue`
In a module
Dim IDValue AS Integer
Sub setIDValue(id As Integer)
IDValue = id
End Sub
Function getIDValue() As Integer
getIDValue = IDValue
End Function
Then from any of your code
'This will set you ID
setIDValue YOUR_VALUE
'This will retrieve the value
getIDValue
'so your code could be
setIDValue Me.Me.lstBoxCompanyName.Value
CompDetailSQL = "SELECT * FROM Companies WHERE Companies.CompanyID = " & getIDValue
Obviously this could use some Error Handling in the event that No IDValue is set. Also I used integer even though I see you are using a String the data type should be the same type as CompanyID so you can change Integer to String if needed but your will also have to change your query to SELECT * FROM Companies WHERE Companies.CompanyID = '" & getIDValue & "' because your query implies a number currently.
You can gain access to another forms controls by specifying the full path. Example :
Forms!MyFormsName!MyControlsName.Value
and
Forms!frmCustomer!CboCustomer.Column(0)
So if you want to access a value in VBA that is contained in another form and use it as part of a query it would look like:
CompDetailSQL = "SELECT * " & _
"FROM Companies " & _
"WHERE CompanyID = " & Forms!frmCustomer!lstBoxCompanyName.Value
in ms Access you can also simply use form_NAMEofFORM.NAMEofCONTROL
Example you can reference
dim myAmount as double
myAmount = form_receipt.total
to access the value showing on form receipt textbox total.

VB.NET 2010 & MS Access 2010 - Conversion from string "" to type 'Double' is not valid

I am new to VB.Net 2010. Here is my problem: I have a query that uses a combo box to fetch many items in tblKBA. All IDs in the MS Access database are integers. The combo box display member and value member is set to the asset and ID of tblProducts.
myQuery = "SELECT id, desc, solution FROM tblKBA WHERE tblKBA.product_id = '" + cmbProducts.SelectedValue + "'"
In addition to getting items from the KBA table, I want to fetch the department details from the department table, possibly done in the same query. I am trying to do it in two separate queries.
myQuery = "select telephone, desc, website from tblDepartments where tblDepartments.product_id = tblProducts.id and tblProducts.id = '" + cmbProducts.SelectedValue + "' "
All help will be appreciated!
Change the '+' to a '&' then the compiler would be happy.
try adding .toString to cmbproducts.selectedvalue or do "tblKBA.product_id.equals(" & cmbProducts.selectedValue.toString & ")"
1.) Don't use string concatenation to build your query. Use parameters.
2.) I am guessing that tblKBA.product_id is a double and not a string, so don't put quotes around it.
myQuery = "SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = ?"
3 things. Test your value before building the select statement. Second, Use .SelectedItem.Value instead of .SelectedValue. Third, protect yourself from sql injection attack. Use parameters, or at the very least check for ' values.
If IsNumeric(cmbProducts.SelectedItem.Value) = False Then
'No valid value
Return
End If
myQuery = String.Format("SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = {0}", cmbProducts.SelectedItem.Value.Replace("'", "''"))

MS access SELECT INTO in vba

I'm having some issues with some functionality of my application. There is a particular instance where I have an instance of a 'pending class' on a form for an administrator to review. The form is populated with students associated with this pending class. After their grades are finished, I have a button at the footer that will delete this class from my 'pending' table and add the grades to all of the students. This works.
However, I want to essentially copy this pending class, which just has the class name, date, and teacher to a completed class table before it's deleted from pending. Since no data about this class other than the primary key(class number) persists throughout this form, I can't populate the other fields(class name, date) of the row into my completed class table.
I am trying a "SELECT INTO" operation in VBA to get these values. It's going like this:
dim cname as String
dim classdate as Date
dim pid as integer
dim teacher as String
dim qry as String
pid = [Forms]![frmClasses]![txtID]
qry = "Select className INTO cname FROM tblPending WHERE tblPending.id = " & " ' " & pid & " ' " & ";"
db.execute qry
debug.print qry
debug.print cname
From here, I do the same operations for each other variable, build my INSERT query, and execute it. The problem is-- my select into's are not working. Debug.print shows that the local variables were never initialized from the SELECT INTO statement. Any thoughts?
First, having all classes in one table and just setting a "NotPending" or "Completed" column would be better.
Having two identical tables for classes and moving values from one into the other to indicate status changes is bad database design.
If you really need to do this by using two tables and copying rows, then you need an INSERT INTO query (and not SELECT INTO), as already mentioned by Remou in the comments, because SELECT INTO creates a new table (or overwrites an existing one with the same name, if already there).
The syntax for INSERT INTO looks like this:
INSERT INTO CompletedClassTable (ClassName, Teacher)
SELECT ClassName, Teacher FROM tblPending WHERE id = 123
And finally, you asked this in a comment:
So SELECT INTO is completely different in Access than Oracle? In Oracle and PL/SQL, you can select a row into a variable OR a table. In Access can you not select into a variable?
To load a row into a variable, you need to use a Recordset.
Example code to load your query into a Recordset and output the ClassName field:
Dim RS As DAO.Recordset
Set RS = CurrentDb.OpenRecordset("SELECT * FROM tblPending WHERE id = 123")
If Not RS.EOF Then
Debug.Print RS("classname")
End If
RS.Close
Set RS = Nothing
Seems you want to retrieve a text value, className, from tblPending where tblPending.id matches the value found in your text box, txtID, and store that text value in a string variable named cname.
If that interpretation is correct, you needn't bother with a query and recordset. Just use the DLookup Function to retrieve the value, similar to this untested code sample.
Dim cname As String
Dim pid As Integer
Dim strCriteria As String
pid = [Forms]![frmClasses]![txtID]
strCriteria = "id = " & pid
cname = Nz(DLookup("className", "tblPending", strCriteria), vbNullString)
Debug.Print "cname: '" & cname & "'"
Notes:
I assumed the data type of the id field in tblPending is numeric. If it is actually text data type, change strCriteria like this:
strCriteria = "id = '" & pid & "'"
DLookup() returns Null if no match found. Since we are assigning the function's return value to a string variable, I used Nz() to convert Null to an empty string. Alternatively, you could declare cname As Variant (so that it can accept a Null value) and get rid of Nz().