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
Related
I am a first time coder with VBA and I am creating a database for data entry at a Psych Lab I work at. Currently the database is created, but I want to prevent duplicate entries from being put into the database (namely by have a code look for the participant number right after it is entered). I have been trying to fix this code for quite a while and I just recently hit a wall. It displays the correct error message when I enter the participant number, however it says that every number has been entered already (even though they actually haven't). Here is the code:
Private Sub Participant_Number_BeforeUpdate(Cancel As Integer)
Dim Participant_Number As Integer
Dim StLinkCriteria As Integer
If (Not IsNull(DLookup("[Participant_Number]", "Entry Log", "[Participant_Number] ='" & Me.Participant_Number.Value & "'"))) Then
MsgBox "Participant Number has already been entered in the database."
Cancel = True
Me.Participant_Number.Undo
End If
End Sub
Any help is greatly appreciated. I have never used VBA before and I am self-teaching how to code.
I guess your Participant_Number field is a number. You shouldn't enclose the criteria with single-quotes ', these are used with fields of text type. Try changing the criteria field from
"[Participant_Number] ='" & Me.Participant_Number.Value & "'"))) Then
into
"[Participant_Number] = " & Me.Participant_Number.Value))) Then
IF you have not used VBA you may try to do this by opening the table in Design view. This method is easy and a good choice. You may have a look here: https://support.office.com/en-us/article/Prevent-duplicate-values-in-a-field-b5eaace7-6161-4edc-bb90-39d1a1bc5576?ui=en-US&rs=en-US&ad=US&fromAR=1
I had an Access Form that works very well for my customer, however they want 3 identical forms, but with different underrunning queries for different types of searches. I could copy and paste the same form and attach the different queries, but this can become a huge maintenance and maintainability issue. Is it possible to use multiple queries on the same form, or change out the query before opening the form?
It sounds like your different queries all return the same SELECT field expressions, but have different WHERE clauses.
If that is true, use a base query without a WHERE clause as the form's Record Source. Then you can essentially add a WHERE clause "on the fly" by using the DoCmd.OpenForm method's WhereCondition option when you open the form.
Const cstrForm As String = "YourForm"
Dim strWhereCondition As String
Load strWhereCondition based on which dataset you want the form to display. These 3 examples assume the form's Record Source includes fields named proj id, proj name, and owner id whose datatypes are numeric, text, and numeric respectively:
strWhereCondition = "[proj id]=" & SomeNumber
strWhereCondition = "[proj name]='" & SomeText & "'"
strWhereCondition = "[owner id]=" & SomeOtherNumber
Then open your form filtered by strWhereCondition:
DoCmd.OpenForm FormName:=cstrForm, WhereCondition:=strWhereCondition
I have an access web database that several users will need to log in to. The database contains a table of products.
The challenge is, every user needs to only see a subset of these products and never see the whole list.
At the moment i have some code to modify an existing query based on the logged in user's details. As they log in, some tempvars are created and these are used to modify the query criteria.
This works well when the first user logs in, but the moment the next user logs in, the query is modified again and the product list refreshes and now his products are shown and not the first users! Im thinking i need to dynamically create a permanent query for each user on log in?
Or is a better way to accomplish what im trying ? im quite new to access and struggling. Can anyone assist please?
Here is my code so far:
Button on login form has the following code that collects the user's details
Private Sub cmdLoginMine_Click()
Dim ID as long, strEmpName as string,strZondsc as string,strgrpdsc as string
ID = DLookup("ID", "Employees", "Login='" & Me.txtUser.Value & "'")
strEmpName = DLookup("FullName", "Employees", "Login='" & Me.txtUser.Value & "'")
strgrpdsc = DLookup("MyGrpdscs", "Employees", "Login='" & Me.txtUser.Value & "'")
strzondsc = DLookup("MyZondscs", "Employees", "Login='" & Me.txtUser.Value & "'")
TempVars.Add "tmpEmployeeID", ID
TempVars.Add "tmpEmployeeName", txtUser.Value
I then call a function that modifies the existing query, populating it with this users details for the criteria
qryEdit strgrpdsc, strzondsc, ID
Sub qryEdit(strgrpdsc As String, strzondsc As String, ID As Long)
Dim qdf As DAO.QueryDef
Dim qdfOLD As String
Set qdf = CurrentDb.QueryDefs("InventoryQryforDS")
With qdf
.SQL = "SELECT Products.ProductCode, Products.ProductName, Products.GRPDSC, Categories.Category, Inventory.Available " & _
"FROM (Categories INNER JOIN Products ON Categories.ID = Products.CategoryID) INNER JOIN Inventory ON Products.ID = Inventory.ProductID " & _
"WHERE Products.GRPDSC in (" & strgrpdsc & ") and Categories.Category in (" & strzondsc & ") and products.ownersid =" & ID & _
" ORDER BY Products.ProductCode"
End With
Set qdf = Nothing
End Sub
The results of the query are shown on a form, which is what is currently requerying and showing the wrong data.
Thanks
EDIT - THe data is shown on a form, linked to one of the new style navigation buttons as shown.The recordsource property of the form is the query that's populated as described above.
I have a few suggestions/corrections to your approach to solving this issue.
When using DLookup, make sure they are enclosed within Nz() function, if the value you are looking for is not found you might be facing troubles of assigning a Null value to a Data Type that cannot handle Null. Anything other than Variant type will suffer.
You seem to do not one but four DLookup's on the table. This could be very expensive. This could be minimized by using a simple RecordSet Object.
I would not use TempVars much as they could be tricky to understand and implement.
Why are you editing the Query? This could again be a bit expensive in terms of memory. How are you showing the list of Products? In DataSheet or ComboBox or LsitBox? You could yet again change the RecordSource or RowSource of the Objects rather than editing the Query itself.
Finally, your users should all have a separate copy of the Front End file. Not one copy used by 20-30 people. If the files is restricted to be used by one person, then the code should work regardless of being modified. As the user will have access to the right data at all times.
I've read through a couple similar posts, but not found a solution for this issue:
I have a form with an unbound rich text, multiline textbox named tbxNote. When the textbox is exited, I use VBA code to create an SQL string which I subsequently execute to UPDATE a table field [Note] with the value in the unbound textbox. [Note] is a "Long Text" field (from my understanding, "Long Text" is equivalent to what used to be called a "Memo" field). The backend is an Access database.
Problem is: Only the first 250 characters of what is in tbxNote get stored in the target table field [Note] even though other "Long Text" fields in other tables are accepting values much longer than 250 characters. So, it does not seem to be an issue with the field type or characteristics in the backend table.
Furthermore, if I manually open the target table and paste 350 characters into the same [Note] field in the target table, all 350 characters get stored. But, if I load up that record into the form or put the same 350 characters into the form's tbxNote textbox, only 250 characters are pulled into tbxNote or saved out to [Note].
Is there a way to store more than 250 characters in an unbound textbox using an UPDATE SQL in code?
In case it matters, here's the SQL code that I used to prove only 250 of 350 characters gets saved to the table field [Note]:
dbs.Execute "UPDATE tblSupeGenNotes " & _
"SET [NoteDate] = #" & Me.tbxNoteDate & "#, " & _
"[SupeType] = " & Chr(34) & Me.cbxSupeType & Chr(34) & ", " & _
"[SupeAlerts] = " & alrt & ", " & _
"[Note] = " & Chr(34) & String(350, "a") & Chr(34) & " " & _
"WHERE [SupeGenNoteID] = " & Me.tbxSupeGenNoteID & ";"
Of course, normally I'd have Me.tbxNote instead of String(350, "a") but the String proves that only 250 of the 350 characters get stored in the [Note] field.
I must be missing something simple, but I cannot figure it out.
Unfortunately, you posted test code works, but you FAILED to post your actual update string that fails. A common (and known) problem is if you include a function (especially aggregates) in your SQL, then you are limited to 255 characters.
In fact this can apply if you have function(s) that surrounds the unbound text box and is used in the query.
So such an update should and can work, but introduction functions into this mix can cause problems with the query processor.
If you included the actual update, then the above issue(s) likely could have been determined.
So the workarounds are:
Don’t use any “functions” directly in the SQL update string, but build up the string.
So in place of say:
Dbs.Execute "update tblTest set Notes = string(350,’a’)"
Note how above the string function is INSIDE the sql.
You can thus place the function(s) OUTSIDE of the query and thus pre-build the string - the query processor is NOT executing nor will it even see such functions.
So we can change above to as PER YOUR EXAMPLE:
Eg:
Dbs.Execute "update tblTest set Notes = ‘" & string(350,’a’) & "’"
(this is how/why your posted example works, but likely why your actual code fails). So functions can (and should) be moved out of the actual query string.
Also make sure there is NO FORMAT in the formatting for the text box, as once again this will truncate the text box to 255.
And as noted here the other suggestion is to consider using a recordset update in place of the SQL update.
Using a recordset can often remove issues of delimiters and functions then become a non issue.
So such SQL updates can work beyond 255 characters, but functions need to be evaluated in your VBA code before the query processor gets its hands on the data as per above examples.
And as noted remove any “format” you have for the text box (property sheet, format tab).
#HansUp's suggested trying a DAO recordset to update the table. That did the trick! Thank you, HansUp. HansUp requested that I post the answer, so, here is the code that worked for anyone else who comes across this thread:
Dim dbs As DAO.Database
Dim rsTable As DAO.Recordset
Dim rsQuery As DAO.Recordset
Set dbs = CurrentDb
'Open a table-type Recordset
Set rsTable = dbs.OpenRecordset("tblSupeGenNotes", dbOpenDynaset)
'Open a dynaset-type Recordset using a saved query
Set rsQuery = dbs.OpenRecordset("qrySupeGenNotes", dbOpenDynaset)
'update the values vased on the contents of the form controls
rsQuery.Edit
rsQuery![NoteDate] = Me.tbxNoteDate
rsQuery![SupeType] = Me.cbxSupeType
rsQuery![SupeAlerts] = alrt
rsQuery![Note] = Me.tbxNote
rsQuery.Update
'clean up
rsQuery.Close
rsTable.Close
Set rsQuery = Nothing
Set rsTable = Nothing
AH! Another bit to the solution is that prior to using the DAO recordset, I was pulling values from the table into a listbox and from the listbox into the form controls (instead of directly into the form controls from the table). Part of the problem (I believe) was that I was then populating the form controls from the selected item in the listbox instead of directly from the table. I believe listboxes will only allow 255 characters (250 characters?) in any single column, so, everytime I pulled the value into the textbox from the listbox, the code was pulling only the first 255 characters into the textbox. Then, when the textbox was exited, the code was updating the table with the full textbox text, but when it was pulled back into the form through the listbox, we'd be back down to 255 characters. Of course, when I switched to the DAO approach, I also switched to reading the textbox value directly from the table instead of pulling it from the listbox.
Moral: Beware of pulling Long Text values through a listbox!
Thanks to everyone who helped me solve this. Sorry for such a newbie error seeming more complicated than it was.
I assume you are using the SqlClient library. In which case, I recommend trying SqlParameters rather than creating a SQL string the way you are. With the SqlParameter you can specify the size of each parameter. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2 . I am a C# dev so my apologies about doing the example code below in C#:
string param = "Hello World";
byte [] encodedStr = Encoding.UTF8.GetBytes(param);
SqlParameter sqlParam = new SqlParameter();
sqlParam.Size = encodedStr.Count; // uses byte count
you could condense it by calling Encoding.UTF8.GetBytes(param).Count. Anyways, this might fix your issue
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.