This is my first post here. Kind of a newbie at Access and I've searched forums to answer my question and tried using similar answers to get my macro working, but I have a syntax error.
I want to click the details button on one form (Employee Profile), and open another form (Employee Training Records) where it will pull up records pertaining to the current employee profile.
In my where condition currently I have:
="[st_no]=" & [st_no] & " AND [emp_id]='" & [emp_id] & "'"
I get a syntax error saying:
(missing operator) in query expression '[st_no]=IEC 62841-2-5 AND [emp_id]='3"
What am I missing?
Since the field st_no looks to be a string, you'll need to enclose the corresponding value with single or double quotes; conversely, since emp_id looks to be an integer, you don't need the surrounding quotes.
As such, I would suggest:
="[st_no]='" & [st_no] & "' AND [emp_id]=" & [emp_id]
Related
I'm attempting to have a user search through a table in Microsoft Access 2010, but the SQL command isn't working. The command that loads and refreshes the table is this:
SELECT Equipment.equipmentID, Equipment.equipmentName, Equipment.model,
Equipment.make, Equipment.equipmentLocation FROM Equipment ORDER BY Equipment.equipmentName;
This works, but when I try to use a variable (or any normal criteria):
searchItem = Me.searchBox.Value
Me.List64.RowSource = "SELECT Equipment.equipmentID, Equipment.equipmentName,
Equipment.model, Equipment.make, Equipment.equipmentLocation FROM Equipment
WHERE Equipment.equipmentName LIKE '%searchItem%' ORDER BY Equipment.equipmentName;"
I've also tried something like "%10%" instead of the searchItem variable, but the command has the table come up blank with no errors. I suspect the problem is with the Equipment.eqiupmentName as the column name, but I can't quite figure out what's wrong here.
Here's a quick look at what the table looks like:
Try this:
Me.List64.RowSource = & _
"SELECT Equipment.equipmentID, Equipment.equipmentName," & _
" Equipment.model, Equipment.make, Equipment.equipmentLocation FROM Equipment" & _
" WHERE Equipment.equipmentName LIKE '*" & searchItem & "*'" & _
" ORDER BY Equipment.equipmentName;"
User rjt011000 has a valid solution, but I recommend using & for string concatenation in VBA (and Access). For an explanation of + and & see this thread.
Access will not recognize or substitute VBA variables inside an SQL statement. Furthermore, the LIKE operator is fed an SQL string value in this case (inside single quotes... which are inside the double quotes), so even if a VBA variable could be referenced directly inside SQL, Access does not interpret any such thing inside a string value.
Regarding the Access SQL LIKE operator, the multi-character matching pattern is * rather than %. Access also recognizes the operator ALIKE which does indeed honor the ANSI pattern %. See LIKE operator docs and this thread regarding ALIKE.
To be more thorough, the string delimiters and LIKE pattern-matching character should be escaped if you don't want the user inadvertently injecting invalid characters that cause errors in the SQL. Following is an example of escaping a couple of them. There are more elegant ways to handle this for all special characters, but the code and technique are beyond the scope of this answer.
...'" & Replace(Replace(searchItem, "*", "[*]"), "'", "''") & "'...
For the record, although Access SQL will not substitute a VBA variable, it will recognize and call a public VBA function. Normally such a public function must be defined in a normal module, but in context of a form's Record Source query, a form-module method can sometimes be called.
One last technique... It is possible to reference a form control's value directly in SQL. This can be very convenient and reduce extra code, but there are a couple caveats:
The form must of course be open, otherwise Access will interpret the reference as an unknown parameter and display a prompt. This will of course not be a problem if the SQL is always in context of the same form.
Access will sometimes automatically refresh the query when such a referenced control is changed, but it is not always guaranteed. The "timing" of automatic refreshes might not be immediately intuitive. You can call the Refresh method on the control or subform from various form events to force the query to refresh after the value is changed.
Notice that in the following example, the string concatenation is inside the VBA string, so that the concatenation actually happens in context of SQL and not beforehand like in the first code snippet. There is no problem with this, just something to consider since this entire answer revolves around proper string interpretation and concatenation.
But really, the same concern exists for un-escaped pattern-matching characters in the user text. Rather than making the SQL text long and ugly with calls to Replace(), instead create a custom function (e.g. EscapePattern()) that does this for any text and then wrap the control reference with that function. The example does this, although I don't include the code for the special function. Such a function could also be used in the first VBA code snippet to simplify building the SQL text.
Me.List64.RowSource = & _
"SELECT Equipment.equipmentID, Equipment.equipmentName," & _
" Equipment.model, Equipment.make, Equipment.equipmentLocation FROM Equipment" & _
" WHERE Equipment.equipmentName LIKE ('*' & EscapePattern(Forms![Form Name]![Control Name]) & '*')" & _
" ORDER BY Equipment.equipmentName;"
There is always more! Did you see the VBA line continuation in my example? It makes the SQL text much easier to view within VBA editor.
I suspect you are not setting your searchItem variable correctly in the SQL string. I am not too familiar with access string concatenation but try separate the searchItem out of the SQL string and then checking if your RowSource has the value you suspect.
Me.List64.RowSource = "SELECT Equipment.equipmentID, Equipment.equipmentName,
Equipment.model, Equipment.make, Equipment.equipmentLocation FROM Equipment
WHERE Equipment.equipmentName LIKE '%" + searchItem + "%' ORDER BY Equipment.equipmentName;"
I am having trouble querying a column in an Oracle view that shows up when I pull the schema. In fact, it appears as column number 2 when I list it out.
The error indicates ORA-00904 invalid identifier, which from what I have read says the column name I am referencing is incorrect, but I have copied the name directly from Oracle Developer, MSAccess, and the datareader.Schema, all of which appear to have no issues getting to that column.
If I query the column just using a linked table in MSAccess the data also comes right up. All of the examples I have seen referencing a similar issue in which the field is incorrectly typed, which though I acknowledge is still a possibility, seems unlikely in this case given the direct copy from the column list as mentioned.
Other solutions mention putting the name in double quotes, which I am uncertain how to do in VB.NET or if it is even necessary.
Code below:
'Open And Query
oledbCon.ConnectionString = strCon
oledbCon.Open()
oledbCom.Connection = oledbCon
oledbCom.CommandType = CommandType.Text
oledbCom.CommandText = "SELECT AREA_CODE FROM CSITAPPS.DAYSIN_1057"
oledbda.SelectCommand = oledbCom
oledbda.Fill(gdt)
I was able to find a solution working with a co-worker for a couple days. The issue stems from the fact that Oracle Column references are Case Sensitive. Because of this the double quotations were required, which is tricky for VB.net given quotation marks indicate and encapsulate String entries. The solution was to break the string and concatenate chr(34) into it. That in combination with ensuring that the column reference case matched what was in the table it came right up.
"SELECT " & Chr(34) & "Area_Code" & Chr(34) & " FROM CSITAPPS.DAYSIN_1057 ORDER BY " & Chr(34) & "Area_Code" & Chr(34) & " DESC;"
Hello Stackoverflow community!
I have run into an issue and I'd love some advice.
I'm working with MS Access and I am trying to append two particular fields from one table to another; however this implementation is in a form and it gets a little complicated... So, I'll explain everything the best that I can
BACKGROUND INFORMATION:
First and fore most, I have two tables; one of which is a linked excel spread sheet from another directory (who is not willing to change any formatting what so ever, so I CANNOT make ANY changes to this file and it is being updated on a daily basis). This excel spreadsheet is very large and contains somewhere around 50 columns
The other table is not anywhere near as large but has around 20 columns and is meant to extract two columns from the excel spreadsheet (the first column and the third column). I'm trying to make a form for this database to be as user-friendly as possible and not many people in my office are familiar with the technicalities of Access queries and programming in VBA.
THE SITUATION:
On my form, the user will enter data into TextBoxA, from there they will click a button; this button will trigger a search through the linked excel spreadsheet for the data that was typed into TextBoxA. It will then copy the data from Field1 (which was the typed data) and Field3 and append these selected fields into the first two fields of the table in my Access Database. All of this is being done through a segment of VBA code
Private Sub CmdCloseForm_Click()
If IsNull(Me.TextBoxA) Or Me.TextBoxA = "" Then
MsgBox ("Field is empty, please try again!")
Else
Dim VendorNum As String
SearchingValue = Me.TextBoxA
Dim SQL As String
SQL = "INSERT INTO tbleRecord (Field1,Field2)" & _
"SELECT * " & _
"FROM tbleLinkedExcel " & _
"WHERE Field1 = '" & SearchingValue & "';"
DoCmd.RunSQL SQL
End If
End Sub
So the biggest issue here is that in Field1, and every time I try to run the code,
I receive an error; which I am assuming it is because of the space (unfortunately I cannot give the ACTUAL variable names out as it is confidential)
ERROR MESSAGE
The INSERT INTO statement contains the following unknown field name: 'FIELD 1'. Make sure you have typed the name correctly, and try the operation again.
The thing is, is that this 'FIELD 1' variable/name is not in my code, but in the linked excel spreadsheet (again, I am not able to change ANYTHING on this spreadsheet).
Thanks guys!
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
edited following andshrew's answer
I'm just finding my feet in VBA scripting and am a bit stumped with this rather simple bit of code. I suspect it is because I'm not getting the syntax of the Where statement right. The code below should open a form to the one record that matches both filter expressions but instead it opens to a blank record. If I only use one filter expression, it works as desired and opens the form to the correct subset of records. From what I found elsewhere it should be possible to combine multiple filter criteria with an AND, so I'm at a loss why this isn't working.
See below the code for a more extensive description of what I'm trying to do, in case this isn't a simple syntax issue after all.
Private Sub lsPrevObs_DblClick(Cancel As Integer)
Dim Microchip As String
Dim ObsDate As Date
Microchip = Me.Text24
ObsDate = Me.lsPrevObs
DoCmd.OpenForm "frmObservationsEdit", acNormal, , "ObsMicrochip ='" & Microchip & "' AND TrappingDate = #" & ObsDate & "#", acFormEdit
End Sub
Context for this sub:
I have a table containing basic information about individual animals with their microchip number (despite the name it does contain letters and is therefore a string, not an integer) as primary key. Then I have a table of observations, which uses the Microchip number and the observation date as a composite primary key.
I have a form linked to the first table. A text box (Text24) displays the microchip number of the current record and a list box (lsPrevObs) shows the dates of observations for the animal for which there already are records in the observation table. I want to tie some VBA code to the double click event of the list box so that when the user double clicks a date, a new form opens (frmObservationsEdit, DataEntry=No) and allows for that observation record to be edited.
Thanks for looking at this.
Unless the code in your example is incorrect, you're currently using the VBA 'and' command rather than sending a SQL 'and' as part of the Where string.
Simply changing your code as follows to make sure the and is within the quotes should make it work.
DoCmd.OpenForm "frmObservationsEdit", acNormal, , "ObsMicrochip ='" & Microchip & "' and TrappingDate = #" & ObsDate & "#", acFormEdit