MS Access: How to get value of textbox on button click? - sql

This is a complete newbie question, but I couldn't find any solution online (at least nothing to my understanding). I want to make a form with a textbox and a button and on click, the button should take the value written in the textbox, find the row with that ID in a table and change an attribute to unavailable. Normally I would do this with a simple SQL statement:
UPDATE table SET available='NO' WHERE id = *textbox.value*;
What should I write instead of textbox.value so that it works?

You can refer to an open form:
UPDATE table SET available='NO' WHERE id = Forms!MyForm!MyTextbox
Assuming that the form is the main form and not a subform. You can also run SQL in VBA. Make sure you do not update a record via a form and via a query or code at the same time.
Re Comments
In this case, the problem is corruption, something I often forget to watch out for. You will find a good article here : http://www.granite.ab.ca/access/corruptmdbs.htm, including Decompile.

Getting the value from the text box is even easier if:
the query is executed from VBA
the VBA is in the same form as the text box
If I understood the question right, this is the case here.
Then you can just do this:
Dim SQL As String
'case 1: when the id is a string value
SQL = "UPDATE table SET available='NO' WHERE id = '" & Me.NameOfTheTextBox & "';"
'case 2: when the id is a numeric value
SQL = "UPDATE table SET available='NO' WHERE id = " & Me.NameOfTheTextBox & ";"
CurrentDB.Execute SQL

Related

Code for button on form to update table in ms access

I'm trying to create a simple form using unbound combo boxes and a button that updates a table when clicked. I have already created another form that is similar to this that works great, so I tried to replicate it using the appropriate fields, but I get an error message- Run-time error '3061: Too few parameters. Expected 1.
The only two fields on the form are FrameID and FrameLocation and the button is MoveFrame. The table to be updated is StockFrames.
This is the code I have on the on-click event on the button:
Private Sub MoveFrame_Click()
CurrentDb.Execute "UPDATE StockFrames SET frameLocation = " & Me.frameLocation & _" WHERE FrameID = " & Me.FrameID
Me.frameLocation.Value = Null
Me.FrameID.Value = Null
End Sub
I appreciate any help anyone can offer. I'm very new to MS Access. If there is any other information that you need as far as the property settings, please let me know. I'm eager to learn and to get this form working properly.
Thank you.
If frameLocation is a text field, parameter needs apostrophe delimiters:
='" & Me.frameLocation & "' WHERE.
Remove that underscore character.
Date/Time fields use # delimiter.

Passing a query a parameter [Access 2016]

To make a longer story shorter:
I'm an Access noob, doing a quick-and-dirty conversion of a massive Excel spreadsheet into an Access database. Part of the requirements are to mimic some of the functionality of Excel, specifically, pulling data from a certain table and doing some basic calculations on it (sums, averages, etc.).
I've written a chain of queries to pull the data, count/sum it, etc., and have been testing them by using a manually-entered Parameter (i.e., the kind where the input box pops up and asks you to type a response). Now that I'm ready to drop these queries into a (sub)form, though, I have no idea how to automatically pass that parameter from a box in the form into the subform into the query.
Every query I've written uses a manually-entered Parameter named "MATCHNAME," which holds the name of an individual. In manual testing, if I enter this parameter on one query, all the queries it calls also get that value. So, I think I just need to figure out how to tell the top query what MATCHNAME actually is, and that'll take care of it.
Problem is, I don't know how to do that in Access. If it was any other programming language, I'd do something like "queryXYZ(MATCHNAME);", but I don't think I can do that in Access. Plus, since the values queryXYZ returns are all calculated, I'm not sure how to add an extra MATCHNAME field, nor how to actually make sure that gets read by the queries, nor how to make sure it gets passed down the chain. I've even tried creating a Parameter in design view, then trying to set up Link Master Fields, but the Parameter doesn't appear in that window.
I'd also like to re-run these queries whenever a new record is pulled up, but I'm not sure how to do that either--i.e., the numbers should be current for whatever record I'm looking at.
And, before we go there--I feel like a Relationship is out of the question, as the data itself is auto-generated, and is in rough enough shape to where I can't guarantee that any given key is wholly unique, and large enough (20k+) that, outside of writing a magical script, I can't assign a numerical key. However, I don't know much about Relationships in Access, so please prove me wrong.
(Is this all making sense?)
Do you have any suggestions for me--for how to make a subform read a field on the main form to run its queries on? Alternately, is there an easier way to do this, i.e., to bed SQL calls inside a form?
Thanks very much for your help...
You can use SQL as the recordsource of the subform in the property tab and use the afterupdate event of your matchname field to change yourform.recordsource = "Select * from table where filteredfieldname = & me.matchname & ";" . You can also use sql as the control source of form fields. To pass criteria to filter the subform using the whole table as the recordsource, add an event procedure to your field's after update event like this
`In the declarataions at the top
Global mtchnmfltr as string
Private Sub MATCHNAME_AfterUpdate()
'use the same procedure for Private Sub yourmainform_Current()
mtchnmfltr = "[yourfilterfield] = " & Chr(34) & me.matchname & Chr(34)
'if matchname is not text then just = "[yourfilterfield] = " & me.matchname
with me.subformname.form
.filter = mtchnmfltr
.filteron = true
end with
'Build your sql as a string for your sum avg fields etc. using mtchnmfltr in the where clause
me.yoursumfield.controlsource = "Select...where " & mtchnmfltr & ";"
'etc.
end sub
Or you could throw Matchname into a sql recordsource of the subform and add the function fields to the subform on the same on current and after update events
if me.newrecord = true then
me.dirty = false
end if
me.subform.form.recordsource = "Select Table.Matchname, sum(yourfield) as sumalias, _
(etc.) from yourtable where table.matchname = " & chr(34) & me.matchname & _
chr(34) & Group By table.matchname"
If you are storing your sums etc in a table you need to do it a bit different, since your controls controlsource are bound to fields.
dim strsqlsumfld as string
dim rs as dao.recordset
strsqlsumfld= "Select SUM.....AS sumfldalias where " & mtchnmfltr & ";"
set rs = currentdb.openrecordset(strsqlsumfld)
me.yoursumfield = rs("sumfldalias")
rs.close

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!

Use toggle buttons to update a record in Access

Hopefully not too difficult question but I cannot figure this out and have been unable to find anything searching the forums.
I want to convert the output of my toggle boxes from 1,2,3,4,5 to the text each button displays.
Couldn't find any setting on the toggle boxes properties themselves so decided I would have to write a macro/vba to do it from the table but as it's quite new to me I am struggling on syntax.
I have tried doing this on the inbuilt data macro mainly, but also tried it via a query and vba and still couldn't figure it out.
[don't have any reputation yet so have not been allowed to post pics of my macro attmept]
please help! Any solution using vba, data macro or a query would be great
EDIT
To be specific rather than a message box I want to update field1 in my table "Major Equipment" based off the option group selection this is my latest attempt but still not sure how to reference the option group. Do I need to set grp equal to the option group and if so how? Is it something like forms!myform!optiongroup ?
Option Compare Database
Function MyFunc(grp As OptionGroup)
Dim rcrdset As Recordset
set grp =
Set rcrdset = Application.CurrentDb.OpenRecordset("Major Equipment", dbOpenDynaset)
Select Case grp.Value
Case 1
With rcrdset
.AddNew
![Field1] = "Not Reviewed"
Case 2
.AddNew
![Field1] = "Reviewed"
Case Else
MsgBox "Error"
End Select
End Function
Also just realised since these toggle buttons will be updated by the user and so I probably need an update rather than addnew?
http://i59.tinypic.com/2ym8wet.jpg
Your buttons are part of an Option Group. That is what you must reference. Below is a snippet from my net search.
From the AfterUpdate() event of your Option Group:
Call MyFunc(Me.MyGroup)
... which will use Select Case to evaluate:
Function MyFunc(grp As OptionGroup)
Select case grp.Value
Case 1
MsgBox "Option value is 1."
Case 2
MsgBox "Option value is 2."
Case Else
MsgBox "Huh?"
End Select
End Function
If you are entirely new to VBA, there are a half-dozen things to learn here, but they will serve you well. VBA provides a bit less-friendly-looking start than a macro, but I can tell you have more adventures ahead and I suggest you skip macros. For most needs, VBA will serve you better; and it's much easier to trouble shoot or provide details when you need advice.
To convert this to a useful function, you will fill a string variable rather than raising a message box. Then you can use the string variable to do something like run an update query. Your latest edit suggests you will go for something like:
strSQL = "UPDATE [Major Equipment] " _
& "SET Field1='" & strUserSelection & "' " _
& "WHERE MyID=" & lngThisRecord
DoCmd.RunSQL strSQL
Your last edit proposes using a DAO recordset. I think you might be fine with the humble DoCmd. Less to learn. You can hammer out a prototype of the query in good ol' Access; then switch to SQL View and paste the query into your VBA module. Insert variables as seen above, taking care with the quote marks. If it doesn't work, use Debug.Print to grab the value for strSQL and take that back to good ol' Access where you can poke at it into shape; use your findings to improve the VBA.

How to stop Access from thinking my table.field in VBA is a form component?

So I'm writing a SQL query in VBA in Access 2010, and when this code is ran, it thinks that SupplierConnect.MailboxID is a component on a form, where it is in fact a database table (SupplierConnect) and field (MailboxID). Every time that code is ran it pops up a box asking me for input from that form component, which actually isn't one. Is there any way to get around this or code this differently?
Thanks!
' Mailbox ID
If IsNull(MailboxIDComboBox.Value) Then
Else
If firstWhere = True Then
MailboxID = "WHERE SupplierConnect.MailboxID = '" & [Forms]![SupplierQuery]!MailboxIDComboBox.Value & "'"
firstWhere = False
Else
MailboxID = " AND SupplierConnect.MailboxID = '" & [Forms]![SupplierQuery]!MailboxIDComboBox.Value & "'"
End If
End If
This is not popping up asking you for this value because it thinks it is a form control, it is because it is undefined to the query. It cannot find the field within query definition. This usually happens because you do not have the proper case sensitive table or field id or the incorrect table is linked. If you provided more code for the SQL statement you are using from beginning to end and your Exact table structure we can narrow down the mistake.