I am very new to MS Access. I have created a database My_database.mdb with a form that displays some fields. The primary key is a field named Ticket.
When I hit the "Search" button, I want to take the numerical value from the Ticket's text field and search for that number in database under 'Ticket' field.
If the number exists, I want to execute some set of instructions, if it does not, I want to execute other set of instructions.
What code should be in the Command_Click function?
At first blush, seems this would do the trick:
(I'm assumming "Ticket" is a numeric data type)
If Not IsNull(Dlookup("[Ticket]", "[My Table]", "[Ticket] = " & [Ticket].Value)) Then
'It found the record, so go do something...
Msgbox "Woo Hoo...I found it!"
Else
'Didn't find anything, so do something else...
Msgbox "Nope. Nada. Nothing."
End if
Replace the above with your table and field reference as applicable.
Related
I am fairly new to access and I am working on a database to manage Bills of Materials (BOMs) of several products. I would like to create a form where the user can input a list of component names to see where these components are being used.
To run a query based on one word is simple but I am struggling to extend it to more than one word.
I would like the user to input the components separated by new lines like this:
Item1
Item2
Item3
...
If I use the text field as is then the query won't find anything because it takes the text field as a whole and not line by line.
I have tried to process the text field into a ListBox because I thought that it would be handled like an array but it does not have a <value> therefore it will not return any search results.
My next try was to use a second text field where I can format the information to the format "Item1";"Item2";"Item3" so that I can use it in an in statement.
If I directly put:
in ("Item1";"Item2";"Item3")
In the query criteria then it will run as expected, however if I try to reference the HelpText (which contains: "Item1";"Item2";"Item3") like so:
In ([Forms]![Search_mult_component]![HelpText])
Then I get no results. I have also tried formatting the text to include the parenthesis like so ("Item1";"Item2";"Item3")
As I mentinoed I am just getting to know Access therefore I am not sure if this is a good practice or if I am trying to force something which can be done in a simple way with a slightly different approach.
Thank you for the support in advance!
You can't. Just like table and field names, the value string of an IN statement must be present before the query runs.
Your only option is to write the SQL string dynamically and, say, create a temporary query to which you pass the SQL.
Using a list box to represent the selection criteria is a good approach as it will allow the user to select & manipulate multiple items as distinct elements, without having to worry about delimiters and such.
However, rather than attempting to access the value of the list box, I would suggest using the list box to populate an underlying table, which you can then join to the relevant field in your query, causing the results to be automatically filtered without the need for a where clause.
I have managed to solve it after #Lee Mac provided the spark!
I created a Table TempTable to store the input values and I was able to use this table in the query later. It still took some code to get there though!
In the form I used a textbox with the multiline data as defined in the question and a button to run the Query. The steps therefore are somewhat separated between the Textbox itself and the button.
The Textbox has the following code for the AfterUpdate event:
Private Sub search_text_AfterUpdate()
Dim TempTable As DAO.Recordset
Dim i As Integer
Dim allNums() As String
' ======= Open table =======
Set TempTable = CurrentDb.OpenRecordset("SELECT * FROM [TempTable]")
' ======= Clear table =======
DoCmd.SetWarnings False 'Disable warnings. If not disabled the user will be prompted to confirm the delete
DoCmd.RunSQL "DELETE * FROM TempTable" 'SQL statement used to delete all entries from a table
DoCmd.SetWarnings True 'Enable warnings
' ======= Process multiline text =======
allNums = Split(search_text.Value, vbNewLine) 'Split the multiline text
For i = LBound(allNums) To UBound(allNums) 'process line by line
If (StrComp(Trim(allNums(i)), "", vbTextCompare) > 0) Then 'Check if current text is empty string
TempTable.AddNew 'Add new Record to table
TempTable![ToSearch] = (Trim(allNums(i))) 'Fill in the text, trim whitespaces
TempTable.Update 'Update Table. Seems to be necessary for changes to take effect
End If
Next i
' ======= Clean up and close table =======
TempTable.Close 'Close the table
Set TempTable = Nothing 'No idea why this is needed :D
' ======= Refresh table =======
'DoCmd.SelectObject acTable, "TempTable"
'DoCmd.Requery
'DoCmd.GoToRecord acDataTable, "TempTable", acLast
End Sub
This code takes care of clearing the table TempTableand filling it with the new input. TempTable has two columns ID and ToSearch where ID is the primary key for the table and ToSearch will be populated with the input from the textbox. I have seen during the testing that when the entries from the table get deleted the new items will still receive new keys when added which worries me because the keys might run out at some point. This is a problem for the future but if you have any advice on this (for example removing the key from the table or sthing) then please let me know.
The code runs after the user hits an enter on the text field but needs a Requery of the table to take effect! This is included in the Button macro:
First the table oject is selected and a Requery is run. After this I close the table and open the actual Query which also needs to be requeried to show the correct updated values.
With this solution I was able to do what I intended to do without having to delve into the depths of SQL.
As always, I appreciate your comments!
I am working on a database where each unique record is for a different destination. Can you set up parameter fields to prompt for entry on each unique record or is it for the field as a whole?
Here is a short outline in english, that is not code and will not run, but does give the idea. I am puzzled by "parameter fields", and also do not know what happens to the "prompt" data after it is entered. This procedural outline might be expanded upon and detailed, and then used as a basis for writing the actual code that will run.
myRecordset = run myQuery
while myRecordset <> EOF
if myRecordset.Fields("X") = "99" then
Show record values for "X" and "Y" and emptyPrompt
endif
myRecordset.MoveNext
End while
I have a Database in Access 2010 where the 1st field is a unique membership number. The field is set Indexed, no duplicates. If a duplicate is entered on the input form no error message is displayed and nothing else works until a unique number is entered. I need the code that would trap the error on the number field losing focus so that a message box would tell the user the problem and then set focus back to the number field or let the user cancel all input.
This is what I have and it causes Datatype errors
Private Sub Grumpy_No_BeforeUpdate(Cancel As Integer)
If DLookup(Str("[Grumpy_No]"), "Grumpy", Str("[Grumpy_No]") = Me!Str(Grumpy_No)) Then
MsgBox "Number has already been entered in the database."
Cancel = True
Me!Grumpy_No.Undo
End If
End Sub
Any clues as to where I am going wrong would be very much appreciated
Looks to me like you're heading in the right direction but you need to fix your DLookup expression. Its third argument must be a single string. I don't see why Str() is useful --- just build a string. Actually I would use DCount instead of DLookup, but then the same issues still apply.
Private Sub Grumpy_No_BeforeUpdate(Cancel As Integer)
If DCount("[Grumpy_No]", "Grumpy", "[Grumpy_No] = " & Me!Grumpy_No.Value) > 0 Then
MsgBox "Number has already been entered in the database."
Cancel = True
'Me!Grumpy_No.Undo '<- consider allowing the user to see the value which failed
End If
End Sub
Note, if you can make Grumpy_No an autonumber primary key, Access will supply unique values automagically, so you wouldn't need your own code to check those values.
I am fairly new to Access and I am having some trouble figuring out how to perform a search.
I have a table that contains records with multiple fields and one primary key field called "Serial".
I have created a form that is linked to this table and all it contains is a text box and a button where the user can type in any word or serial number and anything and the table will be searched for records that have a field that matches the criteria entered.
I have gotten to the point where I can search through the table and find any record with a match but I cannot figure out how to post this record (and any other records that match) to a newly created report so that the user can see all of the results that matched his criteria.
The code I have is as such and the output gives only a blank report.
The msgbox line always outputs the correct Serial number for every search.
I believe that the issue is related to the DoCmd.OpenReport line.
Do While Not rs.EOF 'iterate through table and check all fields
For Each Field In rs.Fields
If Field = SearchBar.Value Then
found = True
MsgBox (rs.Fields("Serial")) 'debugging
**DoCmd.OpenReport "Asset Inv", acViewReport, , "[Serial] = '" & rs.Fields("Serial") & "'"**
Exit For
End If
Next Field
If found Then
Exit Do
Else
rs.MoveNext
End If
Loop
Thanks for the help!
If you Want To search in Multiple Fields Based On one Keyword Do the Following Steps :
1- Suppose we have the following table That Want to search using a keyword in multiple fields
2- Open The Query Design And Choose You Table That You Want Search It
3 - Add Fields To The Query By Dbl Clicking On Desired Fields
4-Now Click On a Blank Column And Go To Design Tab
5-Save You Query
5-Click On Builder
6-Select Your Saved Query From The List
7-Select Fields You Want To Search in And Append Them
concatinate Fields That You Want Search in
8-Now You Have The New Column That Contained All Desired Fields
9-Now In Criteria Section Type Like ""+[]+""
10-Run The Query
Write "Like" Sql Command And Run Query
Enjoy It ...
I am selecting a name from a combo box, I want access to detect if the name is already in the database and display msgbox if there is a duplicate.
I am using the following code, which is not working:
If cboAdvisor.Value = [tblActive_coahing]![Advisor] Then
MsgBox
'do not save record
end if
Any help is appreciated
I believe you need to replace your 'If' statement with a search of your table (is there other related code that you didn't show?) What are the actual values of cboAdvisor.Value and [tblActive_coahing]![Advisor]?
You should obtain the value and then run a query against your table.