Input variable in Where clause for SQL "Select Statement" - Access, VBA - sql

Need help for the below listed issues.
I am getting "YearN" as user input to the select statement to Run a Query in VBA for Access Database. The statement works when a number directly entered in where clause say "2027". Not sure how to reference a input variable/object. Please help.
Need help to refresh the record as I am getting runtime error whenever the code trying to execute line "A.open strconnection" saying "The database has been placed in a state by user 'Admin' on machine that prevents it from being opened or locked". Please advise
Dim YearNumber As Long
DoCmd.RefreshRecord
YearN = InputBox("Enter the Record Year to delete:")
If YearN = "" Then
MsgBox "Year not entered. Query exit"
Else
Dim A As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set A = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\OneDrive - fab\Access_Db\file.Accdb"
strSql = "DELETE FROM APAC_tbl_test WHERE Year= YearN;"
DoCmd.SetWarnings False
A.Open strConnection
Set rs = A.Execute(strSql)
DoCmd.SetWarnings True
Set rs = Nothing
A.Close
Set A = Nothing
End If
End Sub```

If you are trying to have a "pop-up" box where the user inputs a value for the WHERE clause within Access, you don't necessarily need VBA code. Simply write your SQL statement and in the WHERE clause you'll do something like below:
DELETE FROM APAC_tbl_test WHERE Year = [Enter Year:]
Once you run the above code it should prompt user for the year with "pop-up" box that is labelled "Enter Year".
So basically,
WHERE [column name] = [custom prompt message:]
Important to keep the brackets [ ] and the semicolon :.
More information can be found at this link - https://support.microsoft.com/en-us/office/use-parameters-to-ask-for-input-when-running-a-query-c2806d3d-d500-45a8-8507-ec6af351b6ed

Related

MS-Access VBA DoCmd.RunSQL issue

I'm trying to run some SQL from a button however I keep getting runtime error 2342 "A runSQL action requires an argument consisting of a SQL statement." I know the statement works when I run it direct.
As far as I can see I have set it up exactly as per the example in the dev centre documents but it's still failing - code details below, any advice on what I am doing stoopid gratefully received! Thanks
Example in document:
Public Sub DoSQL()
Dim SQL As String
SQL = "UPDATE Employees" & _
"SET Employees.Title = 'Regional Sales Manager'" & _
"WHERE Employees.Title = 'Sales Manager'"
DoCmd.RunSQL SQL
End Sub
My code:
Private Sub btnTestNextSeqNum_Click()
Dim GetSeqNum As String
GetSeqNum = "SELECT dt1.MaxAccSeqNum FROM (SELECT Item.AccessionYear AS AccYear, Max(Item.AccessionSequenceNumber) AS MaxAccSeqNum FROM Item GROUP BY Item.AccessionYear) AS DT1 WHERE dt1.AccYear = 2020;"
msgbox GetSeqNum *this shows that the variable does contain the full SQL statement
DoCmd.RunSQL GetSeqNum
End Sub

How can I add criteria based on a form field to an Access query?

How do I get an operator to work in a query criteria based on a form field. Ideally I would like it to be something like:
IIf([Afloat]="No",<[Forms]![DASF]![Text222],"")
When I remove the operator it finds anything exactly to the criteria in that field but the moment I try to put an operator like greater than or less than it does not work. I am trying to find all records less than the value in that form field.
Any advice on how I can fix this? Or is it not possible in MS Access?
QBF (Query By Form) can't accept operators in the formula. Your only option is to write the query on the fly. You can use the CreateQueryDef method to define the SQL in a specific query, and attach your form or report to the specific query name.
Something like:
Dim db as Database
Dim rec as Recordset
Dim qdf As QueryDef
Dim strSQL as String
Set db = CurrentDB
On Error Resume Next
'First, delete the query if it exists
db.QueryDefs.Delete "MyQueryName"
'Then, set up the query string
strSQL = "Select * From MyTable Where MyField < " & [Forms]![DASF]![Text222] & " and [Afloat] = 'No' "
strSQL = strSQL & "UNION "
strSQL = strSQL & "Select * From MyTable Where MyField = '' and [Afloat] <> 'No' "
'Now, recreate the query
Set qdf = db.CreateQueryDef("MyQueryName", strSQL)
DoCmd.OpenQuery qdf.Name
You could try changing the first criteria to:
>IIf([Afloat]="No",[Forms]![DASF]![Text222])
And then add a second criteria below it in the Or line:
=IIf([Afloat]<>"No","")
I ended up solving my problem by separating it into two separate queries. Below are my steps:
Instead of having a logical expression to decide I separated it into
FLOAT and NONFLOAT queries.
Then I created a command button to open
each query depending on the criteria in a combo box (yes or no).
Here is the code:
Private Sub Command2_Click()
DoCmd.SetWarnings False
If Me.Combo272 = "Yes" Then
DoCmd.OpenQuery "DASF_AGED_AS1_FLOAT", acViewNormal, acEdit
Else
DoCmd.OpenQuery "DASF_AGED_AS1_NONFLOAT", acViewNormal, acEdit
End If
End Sub
This created another problem, I was still unable to reference the txt boxes necessary for my query criteria. To solve this, I made all the text boxes unbound by using the below VBA to auto populate the text boxes based on another combo box. Here is the VBA I used:
Me.Text220 = DLookup("REGION", "TDD_TABLE", "[ID]= " & Me.Combo236)

Set Text Box equal to Query

I have a query in an Access Db that counts the number of observations that meet a certain criteria as defined by two comboboxes. The query works fine, and I can get the result of the query to display and update live with the comboboxes using subforms, but the subforms are an extremely ugly way to represent a single number.
I would like to use a textbox to display that single number from the query instead of a subreport. I've tried inputting the SQL of the query into the Control Source and the Default Value, but no success.
After reading through the forum it appears I can write a function and then set my control source equal to that function.
Here is my VBA:
Public Function AdultCount()
Dim rs As Recordset
Set rs=CurrentDb.OpenRecordset("Select Count([name]) as [# Vars] from Masterdb where ((masterdb.year=[forms]![Masterform]![NavigationSubform].[form]![year]) and (masterdb.recipient=[forms]![Masterform]![NavigationSubform].[form]![recipient]) and (masterdb.group="adult"))")
AdultVar=rs!Result
rs.Close
Set rs=Nothing
End Function
I get "compile error: Expected:list separator or )"
and it highlights "adult" at the end of my SQL query.
I don't know why this isn't working. Does anyone know why I'm getting this error, and tell me if I'm even doing the right thing to get what I want?
edit:
I now have
Dim strSQL AS String
strSQL = "Select Count([name]) as [# Vars] from Masterdb where [year] = " & Me.NavigationSubform.year.value & " and [recipient] = " & Me.NavigationSubform.recipient.value & " and [group]='adult'"
Set rs=CurrentDb.OpenRecordset(strSQL)
AdultVar=rs![# Vars].Value
rs.Close
Set rs=Nothing
End Function
But the textbox reads "#Name?"
Any ideas?
The double quotes for "adult" are throwing the error because you're closing and reopening a string without telling VB what to do with adult"))"). SQL needs single quotes anyway, so change it to 'adult' and the error will go away.
A second option is to build your string first, like so:
Dim strSQL AS String
strSQL = "Select Count([name]) as [# Vars] from Masterdb where [year] = " & Me.NavigationSubform.year.value & " and [recipient] = " & Me.NavigationSubform.recipient.value & " and [group]='adult'"
Set rs=CurrentDb.OpenRecordset(strSQL)
If you're not familiar with using the Me keyword, do a bit of reading up as it will shorten your code and save you time.

count the number of rows in sql query result using access vba

I am trying to count the number of rows in sql query result using access 2007 vba.
What I have is a text box named AGN when a user put value on it check for this value then it bring back MsgBox if the the value is already inserted. What I try to do is :
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT agencies.[agency no] FROM agencies WHERE agencies.[agency no]= " &Me.AGN.Text
Set rs = db.OpenRecordset(strSQL)
If rs.Fields.Count > 1 Then
MsgBox "this value is already here "
End If
Set rs = Nothing
When I insert any value on the textbox I got run time error 3061 (too few parameters)
The "too few parameters" error message generally means there is something in your SQL statement which Access doesn't recognize as a field, table, function or SQL keyword. In this case, it could happen if [agency no] is text rather than numeric data type. If that is the case, enclose the value of AGN with quotes when you build the SQL statement. (Or you could use a parameter query to avoid the need to quote the text value.)
strSQL = "SELECT a.[agency no] FROM agencies AS a" & vbCrLf & _
"WHERE a.[agency no]= '" & Me.AGN.Value & "'"
Debug.Print strSQL
In case of trouble, go to the Immediate window and copy the output from Debug.Print. Then you can create a new query in the Access query designer, switch to SQL View and paste in the statement text for testing.
Once your SELECT is working, you can check whether or not the recordset is empty. When it is empty both its BOF and EOF properties are true. So to detect when it is not empty, check for Not (BOF And EOF) ...
With rs
If Not (.BOF And .EOF) Then
MsgBox "this value is already here "
End If
End With
However you don't actually need to open a recordset to determine whether a matching row exists. You can check the value returned by a DCount expression.
Dim lngRows As Long
lngRows = DCount("*", "agencies", "[agency no]='" & Me.AGN.Value & "'")
If lngRows > 0 Then
MsgBox "this value is already here "
End If
Notes:
I used AGN.Value instead of AGN.Text because the .Text property is only accessible when the control has focus. But I don't know where you're using that checking code, so unsure which is the proper choice for you.
Notice the similarities between the SELECT query and the DCount options. It's often easy to translate between the two.

Using NT login as part of SQL query run via VBA in Access 2007

In Access 2007, I'm trying to use the NTlogin to retrieve a value from a table via a SQL query (see code below). WHen the form loads, I get an error message saying "Compile Error: Expected Function or Variable". Can someone tell me how to fix this error.
Private Sub Form_Load()
Dim UserName As String
Dim strSQL As String
Dim strDept As String
UserName = Environ("USERNAME")
strSQL = "SELECT DEPT FROM IDs WHERE NTLOGIN =" & UserName
strDept = DoCmd.RunSQL(strSQL)
cmdSave.Enabled = False
cmdEdit.Enabled = True
cmdPrevious.Enabled = True
cmdNext.Enabled = True
End Sub
I haven't touched Access for some time, so I don't recall: is Environ("USERNAME") returning the USERNAME environment variable?
If so, then you have a security hole in your code. Specifically, you're open to a SQL Injection attack.
Imagine that before they run Access, a user sets the USERNAME environment variable to something like
''; DROP TABLE IDS;
In that case, you'll be executing the statement:
SELECT DEPT FROM IDs WHERE NTLOGIN =''; DROP TABLE IDS;
You may not want that to happen...
You cannot use RunSQL with a select statement. It is only for action queries.
If you want a recordset, you can say, amongst other things:
strSQL = "SELECT DEPT FROM IDs WHERE NTLOGIN ='" & UserName & "'"
Set rs=CurrentDB.OpenRecordset(strSQL)
Where rs is DAO.Recordset