Separating multiple search criteria with a comma - vba

I am using an Access form to search a table using different textboxes, i.e. Title, Author, Date etc.
Right now I use this code to perform the search, and update a subform with the results:
Private Sub sFindData(strTitle As String, dtmDate As String, strAuthor As String)
On Error Go to E_Handle
Dim strSQL As String
If Len(strTitle) > 0 Then
strSQL = strSQL & " AND Title LIKE '*" & strTitle & "*' "
End If
If (IsDate(dtmDate)) Then
strSQL = strSQL & " AND DocumentDate=" & Format(Me!txtDate, "\#mm\/dd\/yyyy\#")
End If
If Len(strAuthor) > 0 Then
strSQL = strSQL & " AND Author LIKE '*" & strAuthor & "*' "
End If
If Left(strSQL, 4) = " AND" Then
strSQL = " WHERE " & Mid(strSQL, 5)
End If
strSQL = "SELECT Title, DocumentDate, Author FROM tblDocument" & strSQL
Me!sSubTable.Form.RecordSource = strSQL
sExit:
On Error Resume Next
Exit Sub
E_Handle:
MsgBox Err.Description & VbCrLf & VbCrLf & Err.Source & VbCrLf & VbCrLf & "sFindData", vbOKOnly + vbCritical, "Error: " & Err.Number
And I use this code to call sFindData through textboxes on the form:
Private Sub txtTitle_Change()
Call sFindData(Nz(Me!txtTitle.Text, ""), Nz(Me!txtDate, #12/31/2099#), Nz(Me!txtAuthor, "")
End Sub
I have a Change Sub for every textbox in the main form, each bound to its own field through the same code shown above.
My problem is, I sometimes need to search multiple criteria of the same type (two different document titles for example), and I want to be able to do it in one field if possible, i.e. separate the two criteria with a comma (Title#1, Title#2) and have the code search both of these criteria and show the results on the subform
Thanks in advance

Related

Handling an external Access database within an Access Database with VBA?

So I'm a little confused as to how to handle an external database and current database within VBA code. Below is a sub whose purpose is to update the current Access database with unique entries found in the external Access database.
The external SourceDBPath and SelectedTable is passed in, and I specify the external database and table with the string variable SourceDBTable. Then, in the SQL, I try to pull out entries with values that don't match their coresponding field so only unique entries between the two DBs are inserted into the source database.
(For Example, where source = external:
NOT EXIST sourceDB.SelectedTable.Field1 = currentDB.SelectedTable.Field1 And sourceDB.SelectedTable.Field2 = currentDB.SelectedTable.Field2 And sourceDB.SelectedTable.Field3 = currentDB.SelectedTable.Field3, etc.)
SO, my questions are:
1) Do I need to specify the current database within the SQL (like currentDB.table.field), or will it default to the current database if a table or field is called without a prefix (just table or field, like in the code below)?
2) Ultimately, am I going about this in the right way?
My code:
Private Sub UpdateDatabaseTable(SourceDBPath As String, SelectedTable As String)
Dim SourceDBTable As String
On Error GoTo DBError
SourceDBTable = "[;DATABASE=" & SourceDBPath & "]." & SelectedTable
Call DoCmd.RunSQL("INSERT INTO " & SelectedTable & " " & _
"SELECT Field1, Field2, Field3 " & _
"FROM " & SourceDBTable & " " & _
"WHERE NOT EXISTS( SELECT * " & _
"FROM " & SourceDBTable & " " & _
"WHERE (Field1=" & SourceDBTable & ".Field1 And Field2=" & SourceDBTable & ".Field2 And Field3=" & SourceDBTable & ".Field3"));")
GoTo EndSub
DBError:
MsgBox "Database Error!" & vbCrLf & "Error #" & Str(Err.Number) & ": " & Err.Source & vbCrLf & Err.Description, vbExclamation, "Database Error"
EndSub:
End Sub
NOTE: I derived my SQL by extrapolating and modifying the code found in the solution HERE
You have 2 main mistakes in your code, otherwise, it should work.
Don't specify the tablename for each field. Use an alias instead
You want to escape both the tablename, and the database name, not only the database name
Private Sub UpdateDatabaseTable(SourceDBPath As String, SelectedTable As String)
Dim SourceDBTable As String
On Error GoTo DBError
SourceDBTable = "[;DATABASE=" & SourceDBPath & "].[" & SelectedTable & "]"
DoCmd.RunSQL "INSERT INTO " & SelectedTable & " t " & _
"SELECT Field1, Field2, Field3 " & _
"FROM " & SourceDBTable & " s" & _
"WHERE NOT EXISTS( SELECT * " & _
"FROM " & SourceDBTable & " s1 " & _
"WHERE (t.Field1=s1.Field1 And t.Field2=s1.Field2 And t.Field3=s1.Field3));"
GoTo EndSub
DBError:
MsgBox "Database Error!" & vbCrLf & "Error #" & Str(Err.Number) & ": " & Err.Source & vbCrLf & Err.Description, vbExclamation, "Database Error"
EndSub:
End Sub
I've also removed the deprecated Call keyword. Optionally, you can adjust this further by using CurrentDb.Execute, but that's not needed
Following code from my db SENDS data to OTHER db:
strExtract = gstrBasePath & "Program\Editing\ConstructionExtract.accdb"
CurrentDb.Execute "INSERT INTO Bituminous IN '" & strExtract & "' SELECT * FROM ConstructionBIT;"
gstrBasePath is a Global constant declared in a general module:
Global Const gstrBasePath = "\\servernamehere\Crm\Lab\Database\"
You can use literal string path within your procedure.
Following PULLS data from OTHER db:
CurrentDb.Execute "INSERT INTO Employees SELECT * FROM Employees IN '\\servername\filename.accdb'"

Run-time Error 3131 Syntax Error in FROM clause

Tried scouring the forums for threads similar to mine but couldn't really find anything that would lead me in the right direction. Basically I have a table that has the QA scores for each of the 10 regions and I am trying to populate a text box with a specific region's score depending on the month. I was trying to do this in vba for this form but came across this Run-time error 3131 and I'm not entirely sure what's wrong with my code which seems simple enough to me. Thanks for any help or advice in advance.
Private Sub Form_Load()
Dim strSql As String
strSql = "SELECT tblScorecard.[QA_Overall]" & _
"FROM tblScorecard" & _
"WHERE tblScorecard.[Audit Month] = 'Jan'" & _
"AND tblScorecard.[Region] = '1'"
DoCmd.RunSQL strSql
txtReg1 = strSql
End Sub
Is it not possible you should just add spaces?
tblScorecard.[QA_Overall]FROM as one word?
Private Sub Form_Load()
Dim strSql As String
strSql = "SELECT tblScorecard.[QA_Overall] " & _
"FROM tblScorecard " & _
"WHERE tblScorecard.[Audit Month] = 'Jan'" & _
" AND tblScorecard.[Region] = '1'"
DoCmd.RunSQL strSql
txtReg1 = strSql
End Sub
In order to avoid Error: 2342 A RunSQL:
Private Sub Form_Load()
Dim qdf As QueryDef
strSql = "SELECT tblScorecard.[QA_Overall] " & _
"FROM tblScorecard " & _
"WHERE tblScorecard.[Audit Month] = 'Jan'" & _
" AND tblScorecard.[Region] = '1'"
On Error Resume Next
DoCmd.DeleteObject acQuery, "tempQry"
On Error GoTo 0
Set qdf = CurrentDb.CreateQueryDef("tempQry", strSQL)
DoCmd.OpenQuery ("tempQry")
End Sub
More information found here.
When you use & _, you are not adding a line beak INSIDE the string
Try adding a space at the end of the strings
strSql = "SELECT tblScorecard.[QA_Overall] " & _
"FROM tblScorecard " & _
"WHERE tblScorecard.[Audit Month] = 'Jan' " & _
"AND tblScorecard.[Region] = '1'"

The expression contains invalid date constant

I tried this code first before copying it to my main project (I created new project to test the codes first):
Private Sub posBtn_Click(sender As Object, e As EventArgs) Handles posBtn.Click
On Error GoTo wewe
If posText.Text = "" Then
Call notFound()
Exit Sub
Else
Dim cantFind As String = posText.Text
EmployeesRecordBindingSource.Filter = "(Convert(#_of_Employees, 'System.String') LIKE '" & posText.Text & "')" & "OR (last_name LIKE '" & posText.Text & "') OR (first_name LIKE '" & posText.Text & "')" & "OR (mi LIKE '" & posText.Text & "') OR (position LIKE '" & posText.Text & "')"
If EmployeesRecordBindingSource.Count <> 0 Then
With DataGridView2
.DataSource = EmployeesRecordBindingSource
End With
Else
MsgBox(cantFind & vbNewLine & "The search item was not found!", MsgBoxStyle.Information, "Hey boss")
EmployeesRecordBindingSource.Filter = Nothing
With DataGridView2
.ClearSelection()
.DataSource = EmployeesRecordBindingSource
End With
End If
End If
lul:
Exit Sub
wewe:
MsgBox("Error Number " & Err.Number & vbNewLine & "Error Description " & Err.Description, MsgBoxStyle.Critical, "Reset Error!")
Resume lul
End Sub
In my sample project, this is working. But when I copied it to my main project and run, I got this error: The expression contains invalid date constant '#_ofE_Employees, 'Sytem.String') LIKE '1')OR and so on... Did I missed something? Btw, it is for searching in datagridview. I have also private sub for reset, notfound.
Fields cannot start with the # as it is used for dates.
You might reconsider using signs and numbers when creating fields and variables in both your platform and database because there are chances those are reserved.

Update another table when field is changed

I have a form contains "DateProduced" field. The table bound to it is called "Report".
I try to add after update event to this field and want this event to update "DateProduced" field in Quantity table if ID matches for both.
Me![Text0] displays the ID from Report field
Me![Text4] displays the DateProduced from Report field.
The event code is as below.
Private Sub Text4_AfterUpdate()
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = (#" & Me![Text4] & "#) " _
& "WHERE ID = (" & Me![Text0] & ")"
DoCmd.RunSQL strSQL
End Sub
But i can not succeed.
That date format will fail for values where dd/mm can be interchanged for a valid date. It should read:
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me!Text4.Value, "yyyy\/mm\/dd") & "# " _
& "WHERE [ID] = " & Me![Text0].Value & ";"
DoCmd.RunSQL strSQL
End Sub
A note: You should change the names of Text0 etc. to meaningful names.
I made it work with the following code. Thx
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me.Text4.Value, "dd-mm-yyyy") & "#" _
& "WHERE [ID] = (" & Me![Text0] & ");"
DoCmd.RunSQL strSQL
End Sub

Using form combo boxes apply a filter to a query

I think I am close to this one, but can't work out the filtering process.
tblIndex(PrimaryCat,SubCat,UserID,Year)
tblResults(SubCat,UserID)
My Form has two combo boxes and a button. ComboBox1 has tblIndex.PrimaryCat values and ComboBox2 has tblIndexYear values.
What I want is when the command button in the form is pressed, tblResults opens showing the list of SubCat and UserID values when the combobox values are used as a filter on tblIndex.
Does this make sense?
I have the recordsource of the form set to tblResults. I'm using this, just need to add in filtering somehow:
Private Sub cmdGo_Click()
Dim strSQL As String
strSQL = "SELECT SubCat, UserID " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = [strCat] AND Year = [strYear] " & _
"GROUP BY SubCat, UserID"
DoCmd.OpenQuery "strSQL"
End Sub
EDIT:
I'm not sure if I am allowed to answer my own question but I worked out a solution. I >used INTO to put the results into a temp table I can further manipulate using:
Private Sub cmdGo_Click()
Dim strSQL As String
strSQL = "SELECT SubCat, UserID INTO tblTemp " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = '" & cboPrimaryCat.Value & "' AND Year = '" & >cboYear.Value & _
"' GROUP BY SubCat, UserID"
DoCmd.RunSQL strSQL
End Sub
Worked it out. Can't run SQL without first storing it in a query. Solution is:
Private Sub cmdGo_Click()
Dim qdfCurr As DAO.QueryDef
Dim strSQL As String
strSQL = "SELECT SubCat, UserID " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = '" & strCat.Value & "' AND Year = '" & strYear.Value & _
"' GROUP BY SubCat, UserID"
On Error Resume Next
Set qdfCurr = CurrentDb.QueryDefs("TempQuery")
If Err.Number = 3265 Then
Set qdfCurr = CurrentDb.CreateQueryDef("TempQuery")
End If
qdfCurr.SQL = strSQL
DoCmd.OpenQuery "TempQuery"
End Sub
I think that this sould work. Working with temp tables is more complicated. Imagine that you have 50 queries with their corresponding temp table!
Private Sub cmdGo_Click()
Dim strSQL As String
strSQL = "SELECT SubCat, UserID " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = " & Forms!FormName![strCat] & " AND Year = " & Forms!FormName![strYear] " " & _
"GROUP BY SubCat, UserID"
DoCmd.OpenQuery strSQL
End Sub