SQL Query to VBA and display result in Form - sql

So I have a few Queries already written and my goal is to have a user input certain fields that would change the way the Query is returned, basically having the user change 2 or 3 parameters of the original Query.
First, I'm having problems getting a Query to execute in VBA:
Private Sub QResultButton_Click()
DoCmd.OpenQuery (Readings2009, acViewPreview,acReadOnly)
End Sub
[Readings2009 is a Query I created in Access] This returns a syntax error.
I have also see this done:
strSQL = "SELECT Readings2009.id, Readings2009.othercolumn, Readings2009.another
WHERE Readings2009.something > today() ..."
DoCmd.RunSQL (strSQL)
I can't get either to work. Any help would be greatly appreciated.

In this example, the name of the query must be a string, that is, it must be in quotes:
DoCmd.OpenQuery "Readings2009"
See: http://msdn.microsoft.com/en-us/library/aa220295(office.11).aspx
The other example is for running action queries,not for opening queries to view them.
It would be best to create a form and to use that to display your query.

Related

CurrentDb.Execute Error 3061 and DAO.Recordset Error

On a form, a user is able to select a value of either 1 or 2. This number is on an unbound control called CountVal.
When the user selects the submit button, an update query is ran. The following is the query.
UPDATE UserData_T SET UserQuantity = Forms!MainUser_F!CountVal.value;
The query, when run separately, runs as should. The issue comes when I call it in the submit button click event. I use the CurrentDb.Execute method. This method throws a
3061 error of "Too few parameters'.
I have found through much research that control based parameters do not work with the execute method. It works when I set the value as either 1 or 2 but not through the control. I need to have this dynamic.
I have also tried the DAO.Database.OpenRecordset() method, however I am struggling with looping through each record. Logically, I would gravitate to a for each but I'm not finding any references on using this loop with a DAO recordset. Also, wouldn't looping through the recordset be extremely slow? Could I also add an if statement to the query itself?
In MS Access, stored queries can refer to open form or report controls as parameters. However, queries called via DAO methods like CurrentDb.Execute, do not see the GUI interface and hence cannot evaluate form or report controls.
So to continue using form controls as is, simply save your SQL statement as a stored query and call it with DoCmd.OpenQuery (which do not need to be closed for action queries like UPDATE, INSERT, DELETE). This is the coding counterpart to clicking the stored query via Navigation Pane.
DoCmd.OpenQuery "mySavedUpdateQuery"
Do note the above will raise prompts of data changes. To suppress such prompts, use DoCmd.SetWarnings:
DoCmd.SetWarnings False
DoCmd.OpenQuery "mySavedUpdateQuery"
DoCmd.SetWarnings True
You must concatenate the value to build the SQL:
Dim Sql As String
Sql = "UPDATE UserData_T SET UserQuantity = " & Forms!MainUser_F!CountVal.Value & ""

MS Access VBA issue

I'm making a report in MS Access - what I'm trying to do here is basically APPEND a query to a table that I've already created - I select the first value, change it and update the table. The issue that I'm coming across is - this report will be used by a VB6 application. So the user won't be seeing Access at all.
The thing with my append query is that it needs a USER ID to run (4 digit number). Normally when I run a report in Access I pass the parameters to a form in Access - and I use them to run queries. However, in this case, I need the user to enter a value when appending the query, additionally, when appending a query in VBA it first says "You are about to append a query, are you sure" (or something along those lines), so is there a way to automate that as well, so when I append it nothing happens?
Here is my code for appending and selecting date from the tempTable:
CurrentDb.Execute "DELETE from [tempCompanyMgmt-NOW];"
DoCmd.OpenQuery "qryCompanyMgmt-SUE" - i made this append!
Set rs1 = CurrentDb.OpenRecordset("Select * from [tempCompanyMgmt-NOW]", , dbOpenDynamic)
So as long as I press OK, YES when I get notified of the APPEND process and enter the parameter for USER ID - everything works fine.
Looks like a typo in your markdown, should the 2nd line be:
DoCmd.OpenQuery "qryCompanyMgmt-SUE - i made this append!"
You'll need to remove the reference to the form inside the qryCompanyMgmt-SUE - i made this append! query, and swap it for a parameter name. You can use the Access interface to explicitly add a parameters clause to the query, and then using ADO (or DAO) from VB6, set a parameter value before you open/execute the query.
The "You are about to append a query, are you sure" message is an Access feature (and it can be disabled), so if you want the VB6 application to provide such a warning, then you'll need to create it yourself with a MsgBox.
One option would by putting your append query into the code and filling in the parameter that way.
I don't know your exact scenario, but something like:
If not isValidUserID(me.UserID) Then
msgbox "Please enter a a valid user id"
exit sub
End If
Dim strSQL As String
strSQL = "DELETE * from [tempCompanyMgmt-NOW];"
CurrentDb.Execute strSQL, dbFailOnError
strSQL = "INSERT INTO tempCompanyMgmt-NOW ( FieldName1, FieldName2, FieldName3 ) " & _
"SELECT FieldName1, FieldName2, FieldName3 FROM tempCompanyMgmt WHERE UseriD=" & Me.UserID
CurrentDb.Execute strSQL, dbFailOnError
To validate the user id you could do something like:
If (Len(me.UserID) = 4 And IsNumeric(me.UserID)) Then
or
Public Function isValidUserID(varUserID As Variant) As Boolean
Dim blnRet As Boolean
If Len(varUserID) = 4 And IsNumeric(varUserID) Then
blnRet = True
End If
isValidUserID = blnRet
End Function
To get rid of the MsgBox telling me I'm about to append a query i included this in my module before I open my append query..
DoCmd.SetWarnings False
And I realized once I have the value passed to the form (userID), that value gets passed on as a parameter when my query gets appended. So it's all set. Thanks for all help!

Access VBA SQL fails to execute

Using the following code that generates
Error:(2342) A Run SQL action requires an action consisting of an SQL
statement
Here is the code:
Dim Lping As Variant
Lping = "SELECT dbo_Log_Table.LogID"
Lping = Lping + " FROM dbo_Log_Table"
Lping = Lping + " WHERE (((dbo_Log_Table.LogID)=1))"
DoCmd.SetWarnings False
DoCmd.RunSQL Lping
DoCmd.SetWarnings True
The SQL is copied from the QBE grid and executes from there. I have other such code, but can't see the problem with this.
Thanks in advance
JPL
The problem is that DoCmd.RunSQL runs action statements: Insert, Update, Delete. A select statement doesn't do anything. You have no way of obtaining the results of this query and using them and thus RunSQL doesn't even let you waste your time doing it.
If you want to use the results of this query you'll need to create a QueryDef, a query object and use that, or explicitly generate a recordset. Either way the Query needs to get into a recordset to be used.

Cannot get my SQL to delete all records in a table

I'm very new to using VBA within but what I need to do is simply delete all of the records in a table.
I have first created a module and have the following code within it:
Function DeleteRecords()
DoCmd.RunSQL "DELETE * FROM [7 FUF]"
End Function
I then create a macro which has one command, RunCode.
The Function Name that is passed to this command is DeleteRecords(). When I start to type in to the function name section, it does suggest DeleteRecords, so I'm confident it's seeing the function.
When running the macro, I get the error
The expression you entered has a function name that Microsoft Access
can't find
Any ideas what I'm doing wrong?
Actually the problem is not from the function. I believe your module and your function have the same name hence a conflict. If they do, make sure you change the module's name to something else like: DeleteRecordsMod. It is a known and common issue in access. Also make sure the function is publicly accessible. In your code, you don't really need * for delete everything
DoCmd.RunSQL "DELETE FROM [7 FUF]"
Delete Documentation - Vba - Microsoft
Can't find function issue - vba
You may also want to consider bypassing a macro entirely, and doing something like:
CurrentDB.Execute "DELETE * FROM [table]"
Or
Create a DELETE query and store it in the DB, then do a DoCmd.OpenQuery

How to run a SQL select statement in VB

I have been looking around but can't seem to find out how to do this.
I'm trying to execute a SELECT sql statement in VB that takes in a parameter from a form. For example the user selects a From and a To date and the SQL should take what they selected.
I know that you cannot use the DoCmd.Execute method for SELECT SQL so I would need to open the record set - but how? This is what I have tried so far
Dim recordSet As DAO.recordSet
Dim SQL As String
SQL = "SELECT * FROM tblWebMeetingData"
Set recordSet = CurrentDb.OpenRecordset(SQL)
'More code in here
recordSet.Close
Set recordSet = Nothing
Because this executes without an error I assume it's actually getting the results - so is there a way to see what it is actually returning?
Thanks
First: It's a good advice to rename the recordset to rs, for example, because "recordset" is a reserved name. This is misunderstandable.
This recordset contains the records you queried by your SQL statement. You may access those data by rs.fields("fieldname").value. Move to the next recordset with rs.movenext.
To incorporate the form's control value I use the way to build the full SQL statement prior to opening the recordset. Say the form is named "myform" and the control "mycontrol", you may write some kind of
SQL = "SELECT * FROM tblWebMeetingData WHERE myfield = " & forms!myform.mycontrol.value
Please be sure the form only contains valid values, because any wrong formatted value will directly lead to an SQL execution error.
I hope it was this, what you wanted.
Here you have come sample code about iterating trought RecordSet and using values from it( I hope it helps a bit):
Dim i As Integer
Do While Not rs.EOF
Sheets("D_" & day).Cells(i, 1) = rs.Fields(0).Value
Sheets("D_" & day).Cells(i, 2) = rs.Fields(1).Value
rs.MoveNext
i = i + 1
Loop
rs.Close