How to reference textbox in a MS Access form in SQL - sql

I need to find a way to make SQL pick up the data in a textbox on the form in MS Access. If there is any other way around this I'm sure I can do that as I have spent so much time on it already!
In a textbox on the form is where you write down the primary key your using then click submit. It would run the SQL, but the issue is I can't find how to get primary key in there. It's working as if I put it in '' then the whole SQL works. That's only if there is one choice but I want to be able to put loads of possible numbers in.
I have tried:
textbox.text, [forms]![form1]![textbox], form1.textbox,
Here's my current code:
Dim strQuery As String
strQuery = "UPDATE cwsmeriaid SET Pwyntiau = Pwyntiau + 1 WHERE Rhif_Yswiriant_Gwladol = Forms![frm_Archebiad]![rhifYswiriant]"
DoCmd.RunSQL strQuery

Don't enclose variables in quotes. Referencing form control is a variable. Concatenate variables.
Dim strQuery As String
strQuery = "UPDATE cwsmeriaid SET Pwyntiau = Pwyntiau + 1 WHERE Rhif_Yswiriant_Gwladol = " & Forms![frm_Archebiad]![rhifYswiriant]
DoCmd.RunSQL strQuery
If you want to avoid warning popups with action SQL, either turn warnings off then on with DoCmd.SetWarnings [True/False] or use:
CurrentDb.Execute strQuery

Related

MS Access - SetFocus on multiple text boxes to check if data exists via SQL

The problem I'm facing:
I try to check if inserted text from multiple text boxes is already existing in a table before saving the records to avoid duplicates.
I created a form to enter new members and save them into a table. The key to avoid duplicates is to check the combination of given name, last name and birth date with existing records. (It's most likely that there won't be two person with all three criteria matching)
I have no problem to check the existence for only one text box by setting the focus on the desired box and use the SQL query IF EXISTS...
But since I would need to set focus on several text boxes(IMO) the problem occurs.
Is there a way to set focus on multiple text boxes?
The idea would be to use an IF EXISTS...AND EXISTS statement and I would need to implement the .SetFocus statement for each text box before checking its existence.
I hope you get my point and I would be glad if someone could share some knowledge. :)
Thanks in advance
There seems to be some missing information in order to find the best solution to your problem. so the below response will be based on assumptions as to how your form is working.
I'm assuming you are using an unbound form with unbound text boxes? if this is the case, then you must have a button that is the trigger for checking/adding this information to your table. lets say your command button is called "Save". You can use the following code without the need to .setfocus to any textbox.
Private Sub Save_Click()
Dim db as DAO.Database
Dim rst as DAO.Recordset
Dim strSQL as string
set db = currentdb 'This is the connection to the current database
'This is the SQL string to query the data on your table
strsql = "SELECT * " & _
"FROM [Yourtablename] " & _
"WHERE ((([YourTableName].[FirstName]) ='" & me.FormFirstNameField & "' AND ([YourTableName].[LastName]) ='" & me.FormLastNameField & "' AND ([YourTableName].[DOB]) =#" & me.FormDOBField & "#));"
set rst = db.openrecordset(strsql) 'This opens the recordset
if rst.recordcount <> 0 then
'Enter code to inform user information already exists
else
'Enter code if information does not exits
end if
rst.close 'Closes the recordset
set rst = nothing 'Frees memory
set db = nothing 'Frees Memory
End Sub
Let me know if this code works or if I need to make changes based on your scenario.

Run-time Error 2498 for Append and Make Table Queries Created in VBA

I'm getting a 2498 error and really don't understand why. I'm building a string in VBA and am getting the error with the following line of code...
DoCmd.OpenQuery qdfNew, acNormal
It happened with a very long string created to create the query so I simplified the code as much as possible and am still getting the error.
Here's the code...
Option Compare Database
Option Explicit
Dim dbsFootball As Database
Dim strInsertSQL, strSelectSQL, strIntoSQL, strFromSQL, strOrderSQL, strSQL As String
Dim qdfNew As QueryDef
Sub CreateFormattedData()
Set dbsFootball = CurrentDb()
strSelectSQL = ""
strIntoSQL = ""
strFromSQL = ""
strOrderSQL = ""
strSQL = ""
strSelectSQL = "SELECT [tbl_Raw_League_Data].[Season]"
strIntoSQL = "INTO [tbl_Manip Data]"
strFromSQL = "FROM [tbl_Raw_League_Data]" _
+ "LEFT JOIN Referees ON [tbl_Raw_League_Data].[Referee] = Referees.[Referee from Source Data]"
strSQL = strSelectSQL + " " + strIntoSQL + " " + strFromSQL + " " + strOrderSQL
On Error Resume Next ' If query doesn't exist, error won't stop execution
DoCmd.DeleteObject acQuery, "pgmqry_Create Table tbl_Manip"
On Error GoTo 0 ' Reset error handler
Set qdfNew = dbsFootball.CreateQueryDef("pgmqry_Create Table tbl_Manip", strSQL)
DoCmd.OpenQuery qdfNew, acNormal
End Sub
The source field, [tbl_Raw_League_Data].[Season], is a "Short Text" data type (field size = 7).
If I terminate the VBA code and run the query that was created by the code, it works fine with no apparent errors. However, it will never run the query from within the VBA code.
I was originally getting the error 2498 when using "INSERT INTO" for an append query, but realized that the table could as easily be recreated at code execution time.
I'm lost and would sure appreciate some ideas!
Thanks in advance,
Jason
You are passing the querydef object to DoCmd.OpenQuery when it expects a string referencing name of a stored query object. Consider using the querydef's Name property:
DoCmd.OpenQuery qdfNew.Name, acNormal
Alternatively, use .Execute command from database object using the SQL string variable, bypassing any need for querydef:
dbsFootball.Execute strSQL, dbFailOnError
Or with querydef object, as #HansUp suggests, where you simply execute directly since it is an action query:
qdfNew.Execute dbFailOnError
Do note above two options bring up the regular MS Access discussion, of using stored vs VBA string query. While the former is precompiled and runs through query optimizer caching best plan, the latter can have sql dynamically created (structural components that is like SELECT, FROM and JOIN clauses as both can use passed in parameters). From your code snippet consider saving SQL query beforehand without needing to build it in VBA on the fly, and call it with DoCmd.OpenQuery.

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!

Dynamically create Datasheet from SQL query with VBA in Ms Office Access

I have Access database project connected with Ms SQL Server. Data (tables) is stored in the Ms SQL server and Forms and Reports are stored in the Access .ADP file. It is not possible to create Queries, Tables, Views using Design view but Tables and Views can be created using SQL queries and stored on the server. I don't have Ms SQL Server Management Studio and I can't install it in my computer in my office.
So, what I want is to get a dynamically generated Datasheet of a SELECT SQL query to see results temporarily for data analysis. I have placed a textbox and a button in a form and want to display a datasheet containing the result of the SQL query written in the textbox when the button is clicked.
I tried this but it is not working for me and doesn't seems what I want:
MS Access VBA - display dynamically built SQL results in datasheet subform
I also tried by assigning query to Recordsource property of a form. It is showing blank datasheet, but the navigation pane below the datasheet is showing the actual number of records retrieved. So, it is working but not showing the data.
I tried (from http://www.pcreview.co.uk/forums/create-query-dynamically-vba-t3146896.html):
Dim db As DAO.Database
Dim qd As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
strSQL = "select * from analysts"
Set qd = db.CreateQueryDef("NewQueryName", strSQL)
DoCmd.OpenQuery "db.NewQueryName"
It is showing run-time error 91, Object variable or With block variable not set on the line Set qd = db....
And also (from the same page):
Dim strSql As String
strSql = "select * from analysts"
CurrentDb.QueryDefs("qryExport").SQL = strSql
DoCmd.OpenQuery "qryExport"
Returning same error on the line CurrentDb.QueryDefs.....
Any idea or workaround?
This doesn't seems efficient, but it is working and a bit satisfactory:
DoCmd.RunSQL "IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS " & _
"WHERE TABLE_NAME = 'tv') DROP VIEW tv"
DoCmd.RunSQL "create view tv as " & txtQry
DoCmd.OpenView "tv"
Here I am creating a temporary VIEW (tv) in a button's click event. Before creating the view, I am checking that if a view with the same name exist or not; and if it exist then delete it so that a new view can be created with the same name with different query.
Access ADPs are a whole different beast than the normal MDB that you are probably used to working with. DAO isn't generally used in ADPs, you probably had to add a reference to DAO to get any part of the code above to work. ADPs are designed around using ADO to interact with the source database. If you just want to open a recordset to your data, use something along these lines.
Dim strSql As String
Dim rs as ADODB.Recordset
strSql = "select * from analysts"
set rs = New ADODB.Recordset
Set rs.ActiveConnection = CurrentProject.Connection
rs.Source = strsql
rs.Open
You can then interact with that recordset. If you want to bind that recordset to a form so that you can view the data, you can use:
Set Me.Recordset = rs
This is working how I want:
Dim frm As Form ' create a form dynamically
Set frm = CreateForm
Dim rs As New ADODB.Recordset
rs.Open Replace(txtQry, vbCrLf, " "), CurrentProject.Connection ' replace "enters" (vbCrLf) with space because it was throwing error while executing query!
Dim c As Control
For Each f In rs.Fields
Set c = CreateControl(frm.Name, IIf(f.Type = 11, acCheckBox, acTextBox)) ' if field type is "bit", add checkbox; for other datatypes, add textbox
c.ControlSource = f.Name
c.Name = f.Name ' sets column header to the same name as of field's name
Next
rs.Close
frm.RecordSource = txtQry
DoCmd.OpenForm frm.Name, acFormDS ' open form in "DataSheet" view otherwise it will be in "Form" view
This code is placed in a button's click event.
Other possible datatypes for rs.Fields(x).Type (here, f.Type) are (3 = int, 200 = varchar)

Change a column's Format to Percent using a SQL

I have a query in VBA that Adds a few columns to a table. How can I change the format of the PercentSuccess column to Percent using SQL in VBA?
Here is the code I'm using to add the columns.
strSql5 = " Alter Table analyzedCopy3 " & _
"Add Column PercentSuccess Number, Success Number, prem_addr1 TEXT(50) "
DoCmd.SetWarnings False
DoCmd.RunSQL strSql5
DoCmd.SetWarnings True
I've tried to use Format() but I can't get it to work for changing what I need to change. It only seems to change the things like Number, Text and so on.
You cannot set the Format property using SQL but you can do it through additional VBA code. Also you should know that certain field properties do not actually exist until they are assigned a value of which the Format property is one of them. The code below first gets a reference to the field in question, creates a new Format property with the desired value, and then appends it to the fields definition. The Microsoft Access UI is misleading because it makes you think the property already exists.
Dim db As Database
Dim tdef As TableDef
Dim fdef As Field
Dim pdef As Property
Set db = CurrentDb()
Set tdef = db.TableDefs("analyzedCopy3")
Set fdef = tdef.Fields("PercentSuccess")
Set pdef = fdef.CreateProperty("Format", dbText, "Percent")
fdef.Properties.Append pdef
Finally this code only works if you use the DAO objects; you cannot set this property using ADO.