MS Access search form query - database

I am new to Access and am need of help with multi-text box search form in Access 2016. My form has 6 fields in which users can input data to get search result in the subform. Users would need to have the option to enter search parameters in one or more fields to get results. We have a similar form in an Access 2003 database that people love. I have tried copying and updating the code from the Access 2003 database, but I can't seem to get it to work in the 2016 database. I have spent weeks searching for answers and am at a total loss.
The below code is what I copied from the Access 2003 database and updated for the current database:
Private Sub cmdWCSearch_Click()
Dim strsql As String
strsql = "SELECT * FROM qryWCSearch WHERE ID > 0"
If Not IsNull(Me.WCLastName) Then
strsql = strsql & "And [WCLastName] Like '*" & Me.WCLastName & "*'"
End If
If Not IsNull(Me.WCDOI) Then
strsql = strsql & "And [WCDOI] Like '*" & Me.WCDOI & "*'"
End If
If Not IsNull(Me.WCWorkStatus) Then
strsql = strsql & "And [WCWorkStatus] Like '*" & Me.WCWorkStatus & "*'"
End If
If Not IsNull(Me.WCClaimNumber) Then
strsql = strsql & "And [WCClaimNumber] Like '*" & Me.WCClaimNumber & "*'"
End If
If Not IsNull(Me.WCBodyPart) Then
strsql = strsql & "And [WCBodyPart] Like '*" & Me.WCBodyPart & "*'"
End If
If Not IsNull(Me.WCClaimStatus) Then
strsql = strsql & "And [WCClaimStatus] Like '*" & Me.WCClaimStatus & "*'"
End If
End Sub
In the query I have Like "*" & [Forms]![WelcomePage]![WCLastName] & "*" Or ([Forms]![WelcomePage]![WCLastName] Is Null) under the criteria.
Whenever I run the search I get an error message saying "The expression On Click you entered as the event property setting produced the following error: A problem occurred while Microsoft Access was communicating with the OLE server or ActiveX Control."
Any help in getting this to work would be greatly appreciated!

You need a space in front of all your "And"s:
If Not IsNull(Me.WCLastName) Then
strsql = strsql & " And [WCLastName] Like '*" & Me.WCLastName & "*'"
End If

Related

Search Data in continuous form in MS Access

I have a continuous form in MS Access 2003. The source data is a SQL Server link table. I display all the data by the SQL Server table and under the data I have text boxes to search in the above fields (of the form). I have made a routine for dynamic search which I call from the after_update event of the text box. Previously when I had the data in the MS Access backend it was working properly but now that I moved the data from MS Access backend to SQL Server table (backend) it does not work properly when I hit enter and I can't make my search. Any ideas? Thank you.
My Routine dynamic search:
Private Function DynamicSearch(ctl As CONTROL)
On Error Resume Next
Dim strfilter As String
Dim LikeMember As String
If Len(ctl.Text) > 0 Then
SendKeys ("{F2}")
strfilter = ctl.Text
LikeMember = Replace(ctl.Name, "Search", vbNullString)
If Len(Me.FILTER) > 0 Then
Me.FILTER = Me.FILTER & " AND " & LikeMember & " like '*" & strfilter & "*'"
Else
Me.FILTER = LikeMember & " like '*" & strfilter & "*'"
End If
Me.FilterOn = True
Else
If Me.FilterOn Then
Me.FilterOn = False
ctl.SetFocus
SendKeys ("{F2}")
End If
End If
End Function

How to update MSSQL from Excel using excel VBA

Current Situation
I have a database in MSSQL and currently it is able to link to excel the following way.
Excel table which is connected to MSSQL as follows
MSSQL table as below
Currently if I update my MSSQL table, excel table will update accordingly
What I need
I want the vice versa operation. Means whenever I update the excel table, MSSQL also needs to update. Is this possible?
I am able to do it correctly by using following code
Sub updateSqlFromExcel()
Dim cnn As ADODB.connection
Dim uSQL As String
Set cnn = New connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=myServer; " & _
"Initial Catalog=myDatabaseName;" & _
"User ID=username;" & _
"Password=password;" & _
"Trusted_Connection=No"
Set rngName = ActiveCell
cnn.Open cnnstr
excelId = ActiveCell.Value 'This is just an example
excelSeq = ActiveCell.Offset(0, 1).Value 'This is just an example
excelName = ActiveCell.Offset(0, 2).Value 'This is just an example
uSQL = "UPDATE myTableName SET Name = '" & excelName & "', Seq = '" & excelSeq & "' WHERE ID= '" & excelId & "' "
cnn.Execute uSQL
ActiveWorkbook.RefreshAll
MsgBox "Updated successfully. But please wait until background refresh finish before close excel", vbInformation, "Success"
cnn.Close
Set cnn = Nothing
End Sub
Please change myServer, myDatabaseName, username, passwordand myTableNameaccording to your settings in order for this macro to work. Also please add reference library Microsoft ActiveX Data Objects 2.8 Library. In order to add, press Alt+F11 and then goto Tools --> References. Scroll to Microsoft ActiveX Data Objects 2.8 Library and tick the checkbox. Press ok and you are ready to go.

Quote newly created id in message box after SQL Insert in MS Access

I have a VBA script in MS Access that inserts a new record into a SQL Server table based on some inputs on the form.
Private Sub Allocate_Click()
Dim strSQL As String
strSQL = "INSERT INTO dbo_ALLOCATIONS " _
& "([Employee No],[Device Serial Number],[Start Date]) VALUES " _
& "('" & Me.EmployeeNumber & "', '" & Me.SerialNumber & "', '" & Me.StartDate & "')"
CurrentDb.Execute strSQL, dbFailOnError
Dim ReceiptNo As dao.Recordset
Set ReceiptNo = CurrentDb.OpenRecordset("select ##identity")
MsgBox "Device Successfully Allocated. Receipt ID is " & CurrentDb.OpenRecordset("select ##identity")
End Sub
At the end, I query the ID that was auto-incremented during the insert. I want to then quote this in a Message Box so the user can make use of it elsewhere. How can I get it to quote like that in the MsgBox command? The one I have at the moment causes lots of issues around the fact I can't combine this command, and when using only 'ReceiptNo' it says it's not a string.
There should only ever be a single result in the recordset. Try changing your last line to:
MsgBox "Device Successfully Allocated. Receipt ID is " & ReceiptNo(0)
It is not possible to print an entire recordset. You need to refer to the column that you want to print and loop through the recordset while the end of file is not reached. Then output your column as string. I did not test it though.
While not ReceiptNo.EOF
Msgbox Str(ReceiptNo!Identity)
ReceiptNo.moveNext
Wend

Connection to a Microsoft SQL Database via VBA (ADODB) with the lowest risk to harm the database

im currently looking for a way to connect to a Microsoft SQL Server Database via VBA (ADODB) with the focus on a minimal risk in harming, block and change the structure of the database. Therefor the access is readonly.
My attemp is the following:
Set DBConn = New ADODB.Connection
Set TmpRecset = New Recordset
DBConn.ConnectionString = pConnStr
DBConn.Open
On Error GoTo TermConnection
With TmpRecset
.ActiveConnection = DBConn
.Source = pQuery
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.CursorLocation = adUseClient
.Open
End With
On Error GoTo TermRecordset
//Doing something useful with TmpRecset
On Error GoTo 0
TermRecordset:
TmpRecset.Close
Set TmpRecset.ActiveConnection = Nothing
TermConnection:
DBConn.Close
Set DBConn = Nothing
End Sub
And I'm using the following connection string:
"Provider=SQLOLEDB;Data Source=IP\Database;Initial Catalog=Databasename;Trusted_connection=yes;"
I used the manual error handling to ensure, that the recordset and the database is closed whatever happens. Via the parameters of the recordset I define the readonly access.
Are there some other mechanisms to make sure, that the integrity of the Database will be ensured?
Best regards
In my opinion there is no reasonable security in Excel. All security should reside on the server. If you want to prevent accidental or malicious changes to the database then the database on the server should be read-only or all users should have read-only access to the SQL server. Furthermore, you can implement traces on the server, SQL audit C2, or make use of extended properties. Yet, all of this is on the side of the SQL server. The things you can do on the "client" side (such as Excel in this case) are only support functions. And so the question is (to me) what kind of support functions can I implement in Excel to ensure SQL server safety. Here are some of the things I do:
(1) Make the connection string dynamic using global variables or storing the string on a hidden sheet. Then you can automatically switch between development server and production server. Example:
Dim conRCServer As ADODB.Connection
Dim rstResult As ADODB.Recordset
Dim strSQL As String
Set conRCServer = New ADODB.Connection
conRCServer.ConnectionString = "PROVIDER=SQLOLEDB; " _
& "DATA SOURCE=" & Ref.Range("C2").Value2 & ";" _
& "INITIAL CATALOG=" & Ref.Range("C4").Value & ";" _
& "Integrated Security=SSPI "
On Error GoTo SQL_ConnectionError
conRCServer.Open
On Error GoTo 0
(2) Have a seperate error handler for connecting to the server and handling SQL syntax errors. Example:
Set rstResult = New ADODB.Recordset
strSQL = "set nocount on; "
strSQL = strSQL & "/* #" & ActiveWorkbook.Path & "/" & ActiveWorkbook.Name & "{" & WorksheetUsers.Name & "}btnDownloadUserDataFromServer */"
strSQL = strSQL & "select v.LastName, "
strSQL = strSQL & " v.FirstName "
strSQL = strSQL & "from vUsers as v "
strSQL = strSQL & "order by v.LastName, v.FirstName "
rstResult.ActiveConnection = conRCServer
On Error GoTo SQL_StatementError
rstResult.Open strSQL
On Error GoTo 0
Here is an error handler for the SQL syntax and in the above example is a seperate handler for the possible SQL connection error.
(3) Incorporate self-identification within the SQL syntax. As you can see in the above example I am also letting the server know which file, which sheet (within the file) and which function within the sheet the user called to execute this statement. If you capture this data on the server with a trace then you can see who is writing their own queries, who is using your standard files and which functions are used (and their respective impact).
(4) If an error occurs you might want to consider writing automated error emails. Example:
SQL_ConnectionError:
Y = MsgBox("Cannot connect to the server. Please make sure that you have a working internet connection. " & _
"Also ensure that are connected to the corporate network and are allowed to access the server. " & _
"Do you want me to prepare an error-email?", 52, "Problems connecting to Server...")
If Y = 6 Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = Ref.Range("C7").Value2
.CC = Ref.Range("C8").Value2
.Subject = "Problems connecting to database '" & Ref.Range("C4").Value & "' on server '" & Ref.Range("C2").Value & "'"
.HTMLBody = "<span style=""font-size:10px"">---Automatically generated Error-Email---" & _
"</span><br><br>Error report from the file '" & _
"<span style=""color:blue"">" & ActiveWorkbook.Name & _
"</span>' located and saved on '<span style=""color:blue"">" & _
ActiveWorkbook.Path & "</span>'.<br>" & _
"Excel is not able to establish a connection to the server. Technical data to follow." & "<br><br>" & _
"Computer Name: <span style=""color:green;"">" & Environ("COMPUTERNAME") & "</span><br>" & _
"Logged in as: <span style=""color:green;"">" & Environ("USERDOMAIN") & "/" & Environ("USERNAME") & "</span><br>" & _
"Domain Server: <span style=""color:green;"">" & Environ("LOGONSERVER") & "</span><br>" & _
"User DNS Domain: <span style=""color:green;"">" & Environ("USERDNSDOMAIN") & "</span><br>" & _
"Operating System: <span style=""color:green;"">" & Environ("OS") & "</span><br>" & _
"Excel Version: <span style=""color:green;"">" & Application.Version & "</span><br>" & _
"<br><span style=""font-size:10px""><br>" & _
"Possible reasons for this error include: (1) no Internet connection, (2) no working VPN connection to the corporate network, " & _
"(3) the server is currently offline, (4) DNS authentication problems, (5) ... other reasons ..., " & _
"(6) the user does not have the required permission to connect to the underlying database on the server." & _
"<br><br>---Automatically generated Error-Email---"
.Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
End If
Exit Sub
I also looked into your approach of changing the connection parameters. But in most corporate environments I have worked for these connection parameters have been overridden (for example ADODB.Connection.CommandTimeout is overridden by the server's SQL timeout per user or Windows corporate presets if they exist). So, they did not work for me. But the above worked rather well for me and the companies I worked for over the last couple of years.
Let me know if this is the kind of answer you've been looking for.

Add/Edit Button Giving Datatype Error

I have a main and subform. I have text boxes in the main form that will allow me to add/edit information into the subform. Add works fine but when I try to edit a record, the information of the selected record shows up in the textbox like I want to but when I try to update, I get datatype error. Also when I try to delete a record I also get a datatype error.
Im trying to copy the work one of my partners for a previous project did (CarDealership). Im hoping to get similar functionality into the KeyInventory DB.
Here are the files im using: http://jumpshare.com/b/t7Lot8
I've only done the code for buttons found on the mainKeys form
Error Reproduction: I click remove key, get the conformation dialog. Select yes which produces "Run-Time error "3464": Data Type Mismatch in Criteria Expression"
This is the code for the add/update button:
Private Sub cmdAdd_Click()
If Me.keyID.Tag & "" = "" Then
CurrentDb.Execute "INSERT INTO KEYS(KEY_ID, ROOM, DRAWER)" & _
" VALUES(" & Me.keyID & ",'" & Me.roomID & "'," & Me.drawerID & ")"
subKey.Form.Requery
Else
CurrentDb.Execute "UPDATE KEYS " & _
" SET KEY_ID=" & Me.keyID & _
", ROOM='" & Me.roomID & "'" & _
", DRAWER='" & Me.drawerID & "'" & _
" WHERE KEY_ID=" & Me.keyID.Tag
End If
cmdReset_Click
subKey.Form.Requery
End Sub
This is the code for the Delete button:
Private Sub cmdDelete_Click()
If Not (Me.subKey.Form.Recordset.EOF And Me.subKey.Form.Recordset.BOF) Then
If MsgBox("Confirm Deletion?", vbYesNo) = vbYes Then
CurrentDb.Execute "DELETE FROM KEYS" & _
" WHERE KEY_ID=" & Me.subKey.Form.Recordset.Fields("KEY_ID")
Me.subKey.Form.Requery
End If
End If
End Sub
Assuming this is the line which triggers your "Data Type Mismatch in Criteria Expression" error ...
CurrentDb.Execute "DELETE FROM KEYS" & _
" WHERE KEY_ID=" & Me.subKey.Form.Recordset.Fields("KEY_ID")
... give yourself an opportunity to examine the statement you're asking the db engine to execute. Replace that line in cmdDelete_Click() with this code:
Dim strSql As String
strSql = "DELETE FROM KEYS" & _
" WHERE KEY_ID=" & Me.subKey.Form.Recordset.Fields("KEY_ID")
Debug.Print strSql ' <- prints to Immediate window
CurrentDb.Execute strSql, dbFailOnError
Then, with your form in Form View, click the command button which leads to the error. And when you get the error, go to the Immediate window (Ctrl+g) and view the DELETE statement. If the problem with that statement isn't obvious, you can copy the statement text and paste it into SQL View of a new query for testing. Show it to us if you need more help.
Note: This suggestion will not fix the error. It is intended only to help you diagnose the failing DELETE statement.
If the data type of your KEY_ID field is text, add quotes around the number in your DELETE statement similar to this one:
DELETE FROM KEYS WHERE KEY_ID='7'
If that works, revise the code to also include quotes.
strSql = "DELETE FROM KEYS WHERE KEY_ID='" & _
Me.subKey.Form.Recordset.Fields("KEY_ID") & "'"

Resources