Trouble with DoCmd.OpenReport with a complicated Where Clause (Syntax Issue) - sql

So first I have gone over a very large amount of other sources trying to look for a solution or an explanation of my error, but I haven't found anything that helps me quite yet.
I have been learning all this stuff on my own so I am definitely lacking in some of the foundation knowledge and it has caught up to me. Basically the form I am having trouble with allows the user to generate three different reports based on the kind of criteria they care about. There are three different combo boxes cboCompany, cboProject, cboEmployee. I use the Nz command to change null values to zero and then use If Statements to determine which report to use depending on what the user selects. I hope that kind of makes since. Its easier to show than explain. That part all works fine though.
The problem I'm getting is when I want to do a print preview for the report the user generates. I need the where clause to take the values the user selects to use in the print preview. I can't get the syntax right for the where clause to actually do this.
Here is how I call my variables. The Nz function as I understand require the variables to be variants, because of this I'm not quite sure how to write the syntax for the where clause. I know integers, strings, and dates all have different syntax but I don't know what variant would be.
Dim Company As Variant
Dim Project As Variant
Dim Employee As Variant
Dim EndDate As String
Dim StartDate As String
Company = Nz(cboCompany, 0)
Project = Nz(cboProject, 0)
Employee = Nz(cboEmployee, 0)
StartDate = txtStartDate.Value
EndDate = txtEndDate.Value
So this next part is how I have written one of the report options with my best guess of the syntax for the where clause. It doesn't work so If you could help point me in the right direction I would greatly appreciate it.
ElseIf Company <> 0 And Project <> 0 And Employee <> 0 Then
DoCmd.OpenReport "ProjectReport_Employee_R", acViewPreview, "", "[cboCompany]= " & Company & " And [cboEmployee]= " & Employee & " And [cboProject]= " & Project & " And [txtStartDate]= #" & StartDate & "# And [txtEndDate]= #" & EndDate & "#", acWindowNormal
If I don't explain things well enough or you need more code to help please let me know, and thank you in advance.
***Edit: Just to give a more complete picture this is the code behind the entire form.
Private Sub cboCompany_AfterUpdate()
Me.cboProject.Requery
End Sub
Private Sub cmdSubmit_Click()
'Open Report With Filter Criteria
Dim Company As Variant
Dim Project As Variant
Dim Employee As Variant
Company = Nz(cboCompany, 0)
Project = Nz(cboProject, 0)
Employee = Nz(cboEmployee, 0)
If Company = 0 Then
MsgBox ("Please Select At Least A Company To Generate A Report")
cboCompany.Value = Null
cboProject.Value = Null
cboEmployee.Value = Null
ElseIf Company <> 0 And Project = 0 And Employee = 0 Then
DoCmd.BrowseTo acBrowseToReport, "ProjectReport_Company_R", "Main_F.NavigationSubform>ProjectReport_F.Child31"
ElseIf Company <> 0 And Project <> 0 And Employee = 0 Then
DoCmd.BrowseTo acBrowseToReport, "ProjectReport_Project_R", "Main_F.NavigationSubform>ProjectReport_F.Child31"
ElseIf Company <> 0 And Project <> 0 And Employee <> 0 Then
DoCmd.BrowseTo acBrowseToReport, "ProjectReport_Employee_R", "Main_F.NavigationSubform>ProjectReport_F.Child31"
ElseIf Company <> 0 And Project = 0 And Employee <> 0 Then
MsgBox ("Please Select A Project")
End If
End Sub
Private Sub Form_Current()
Me.cboCompany.SetFocus
End Sub
Private Sub Form_Load()
'Set Date Values
Dim EndDate As String
Dim StartDate As String
StartDate = Format(DateSerial(Year(Date), Month(DateAdd("m", -1, Date)), 16), "Short Date")
EndDate = Format(DateSerial(Year(Date), Month(Date), 15), "Short Date")
txtStartDate.Value = StartDate
txtEndDate.Value = EndDate
'Set The Form Message on Open Child31
DoCmd.BrowseTo acBrowseToForm, "ProjectReport_Message_F", "Main_F.NavigationSubform>ProjectReport_F.Child31"
End Sub
'------------------------------------------------------------
' Print_Click
'
'------------------------------------------------------------
Private Sub Command39_Click()
On Error GoTo Command39_Click_Err
Dim Company As Variant
Dim Project As Variant
Dim Employee As Variant
Dim EndDate As String
Dim StartDate As String
Company = Nz(cboCompany, 0)
Project = Nz(cboProject, 0)
Employee = Nz(cboEmployee, 0)
StartDate = txtStartDate.Value
EndDate = txtEndDate.Value
If Company <> 0 And Project = 0 And Employee = 0 Then
DoCmd.OpenReport "ProjectReport_Company_R", acViewPreview, "", "", acNormal
ElseIf Company <> 0 And Project <> 0 And Employee = 0 Then
DoCmd.OpenReport "ProjectReport_Project_R", acViewPreview, "", "", acNormal
ElseIf Company <> 0 And Project <> 0 And Employee <> 0 Then
DoCmd.OpenReport "ProjectReport_Employee_R", acViewPreview, "", "[cboCompany]= " & Company & " And [cboEmployee]= " & Employee & " And [cboProject]= " & Project & " And [txtStartDate]= '" & StartDate & "' And [txtEndDate]= '" & EndDate & "'", acWindowNormal
End If
Command39_Click_Exit:
Exit Sub
Command39_Click_Err:
MsgBox Error$
Resume Command39_Click_Exit
End Sub

I think you may be using the wrong field names in the filter.
Suppose that in Report Design your report's RecordSource is tblProject.
When you do this:
DoCmd.OpenReport "ProjectReport_Employee_R", , , "[cboCompany]= " & Company ...
you are effectively opening the report with a recordsource of:
SELECT * FROM tblProject WHERE [cboCompany] = 12345 AND ...
If tblProject doesn't have a field named "cboCompany" then it won't work.

I would base the report on a query rather than using the DoCmd's "WhereCondition" argument.
Make the "ProjectReport_Employee_R" recordsource a query called "qryProjectReport_Employee_R".
...then modify the query definition every time you want to run the report.
For example:
sub print_report()
'add these
dim qdf as Dao.Querydef
dim strSQL as String
if this then
ElseIf Company <> 0 And Project <> 0 And Employee <> 0 Then
'SQL may need modifying...
strSQL= "SELECT * FROM SomeTable WHERE [cboCompany]= " & Company & " And [cboEmployee]= " & Employee & " And [cboProject]= " & Project & " And [txtStartDate]= #" & StartDate & "# And [txtEndDate]= #" & EndDate & "#"
Set qdf="qryProjectReport_Employee_R"
qdf.SQL=strSQL
DoCmd.OpenReport "ProjectReport_Employee_R", acViewPreview
'clean up
set qdf=nothing
end if
end sub
That's all. Let me know if you have any questions.

Related

OpenRecordset not returning usable recordset / .edit not working?

Working on a database on Access, trying to run a query to find a record with the latest date and a 'where' condition.
Error returned is "Run Timer Error '3027' Cannot update. Database or object is read-only"
Following conditions:
Button is clicked on a form that contains a text field for 'fCheckInFor'.
Database 'ToolTests' fields
"CheckOut" is dates in format of "3/15/2019 5:35:31 PM"
"CheckIn" is dates in format of "3/15/2019 5:35:31 PM"
"CheckInFor" is a text field
"ToolNumber" is a text field
Public CheckInTool as String
Private Sub CheckIn_Click()
CheckInTool = "000"
If Me.fCheckInFor = "" Then
MsgBox "Enter Returning User."
Else
Dim dbsUE As DAO.Database
Dim rstUE As DAO.Recordset
Set dbsUE = CurrentDb
Set rstUE = dbsUE.OpenRecordset("SELECT Max([CheckOut]) FROM [ToolTests] WHERE [ToolNumber]= '" & CheckInTool & "'")
With rstUE
.Edit 'error occurs here
!CheckIn = Now()
!CheckInFor = Me.fCheckInFor
.Update
End With
MsgBox "Checked In"
DoCmd.Close acForm, "CheckIn"
End If
End Sub
So the error throws at the .Edit line, I'm unsure where to go from here. would also be fine with tossing the whole thing and going at it from a different direction.
If I get you right, you want to update a record that has a specific ToolNumber. So, if you want to use a subquery, you will either need to use that criterion in both the main query and the subquery, or link the subquery with the main query using that field:
Set rstUE = dbsUE.OpenRecordset( _ &
"SELECT CheckIn, CheckinFor FROM ToolTests WHERE" & _
" CheckOut IN (SELECT Max(CheckOut) FROM ToolTests AS tmp WHERE ToolNumber = ToolTests.ToolNumber)" & _
" And ToolNumber = '" & CheckInTool & "'")
Alternatively, you could simply sort the records in the correct order and update the first one:
Set rstUE = dbsUE.OpenRecordset( _ &
"SELECT CheckIn, CheckinFor FROM ToolTests WHERE" & _
" ToolNumber = '" & CheckInTool & "'" & _
" ORDER BY CheckOut DESC")

Use bookmark value in WORD for sql query

I am currently trying to build an automated WORD business letter that fills out corresponding data such as company address, company name, today's date, deadline date and so on after I have typed in a 5 digit number.
The number and all other fields are bookmarks.
Whenever the user types in a specific 5 digit number into the bookmark named "theNumber", this value will be used for an SQL query (Oracle). The query then fills out all other bookmarks!
Here is what I have tried so far:
Function dbQuery(ByVal TM As String, ByVal myNumber As String) As Boolean
Dim sqlrumpf As String
Dim sqlstring As String
Dim connstring As String
With ActiveDocument
If .Bookmarks.Exists(TM) Then
Dim TMRange As Range
Set TMRange = .Bookmarks(TM).Range
TMRange = myNumber
.Bookmarks.Add TM, TMRange
dbQuery = True
Else
Debug.Print "Bookmark not found: " & TM
End If
End With
sqlrumpf = "SELECT p.name " & _
"FROM xy.person p, xy.adresse a, wz.zusatz1 z, xy.vorgang v " & _
"WHERE p.adresse_id = a.adresse_id " & _
"AND z.aktnr = v.vorgang_id " & _
"AND a.adresse_id = v.adresse_id " & _
"AND v.vorgang_nr = '"
sqlstring = sqlrumpf & myNumber & "'"
connstring = "ODBC;DSN=mydsn;UID=myuid;DBQ=my.dbq.lan;DBA=W;APA=T;PFC=1;TLO=0;PWD=mypw;"
QueryTables.Add _
(Connection:=connstring, _
Destination:=Range(TMRange), _
Sql:=sqlstring).Refresh
End Function
Sub Main()
If dbQuery("theNumber", "12345") = False Then
MsgBox "Database query failed!"
End If
End Sub
I get the error:
Runtime Error '4608': Value not within definition range.
How can I fix this?
The error seems to occur here:
Destination:=Range(TMRange), _
Normally I use this query only for excel when I want to print a query into a single cell.
Is it generally a bad idea to use bookmarks with sql queries in this manner?
Which fields would you use if not bookmarks?
How do you query bookmark values?

Access, VBA: Find First not working correctly

I hope this is a simple question for someone. I have this method that uses two form fields to check if a record exists in my table and either adds a record or does nothing. So if patient_id is 100, and visit_number is 1, then I will only add a new record if it doesn't already exist.
So, if rst.NoMatch is true - add a new record. However, I can't get it to recognize a duplicate. Here is the code:
Private Sub add_record_button_Click()
Dim rst As DAO.Recordset
Set rst = Me.RecordsetClone
Dim dbs As DAO.Database
Set dbs = CurrentDb
If IsNull(Form.patient_id) Or IsNull(Form.visit_number) = True Then
MsgBox "Please fill in both fields."
Else
rst.FindFirst "[patient_id] = " & Form.patient_id & " And [visit_number] = " & Form.visit_number
If rst.NoMatch Then
Set rst = dbs.OpenRecordset("Visits")
rst.AddNew
rst!patient_id = Form.patient_id
rst!visit_number = Form.visit_number
rst.Update
MsgBox "New patient visit has been added to the database."
Else
MsgBox "That visit already exists."
End If
rst.Close
End If
End Sub
I believe that my FindFirst line isn't correct. In the database, the variables are named patient_id and visit_number. On the form they are named the same.
Any help would be appreciated, thanks.
EDIT.
From the comments below, I was able to get my logic working but using a different compare feature, Dlookup.
IsNull(DLookup("[patient_id]", "MyTable", "[patient_id] = " & Forms("MyForm").patient_id & " AND [visit_number] = " & Forms("MyForm").visit_number)
FINAL EDIT.
The above line made everything work if I used the form directly, however if I put the form into a navigation form - it stopped working. The string that ultimately got it working from within a navigation form looks like this:
If IsNull(DLookup("[patient_id]", "Visits", "[patient_id] = " & Me!patient_id.Value & " AND [visit_number] = " & Me!visit_number.Value)) = True Then
Thank you all for your help.
I've never seen Form used this way, and you should be able to add the record directly in the form, so try:
Private Sub add_record_button_Click()
Dim rst As DAO.Recordset
Set rst = Me.RecordsetClone
Dim PatientId As Variant
Dim VisitNumber As Variant
PatientId = Me!patient_id.Value
VisitNumber = Me!visit_number.Value
If IsNull(PatientId) Or IsNull(VisitNumber) Then
MsgBox "Please fill in both fields."
Else
rst.FindFirst "[patient_id] = " & PatientId & " And [visit_number] = " & VisitNumber & ""
If rst.NoMatch Then
rst.AddNew
rst!patient_id.Value = PatientId
rst!visit_number.Value = VisitNumber
rst.Update
MsgBox "New patient visit has been added to the database."
Else
MsgBox "That visit already exists."
Me.Bookmark = rst.Bookmark
End If
End If
End Sub

How to remove duplicates from form recordsource in Access

I'm building a rather complex database for my limited (yet slowly growing) knowledge of database and programming. So, I really appreciate your help.
The database keeps track of customers, buildings, rooms, and equipment which is in rooms.
I have a search form which filters a union query I've made that queries almost the entire database. The SQL is below:
SELECT tblcustomer.organizationfk,
tblcustomer.shopnamefk,
tblcustomer.officesymfk,
tblcustomer.lastname,
tblcustomer.firstname,
tblfacilitymgr.buildingfk,
tblrooms.roomspk,
tblbuilding.buildingname,
tblrooms.roomname,
tblcabinet.cabinetname,
tblequipment.cabinetfk,
tblequipment.equipmentnamefk,
tblequipment.equipmentbrandfk,
tblequipment.equipmentnetworktypefk
FROM ((tblbuilding
INNER JOIN tblrooms
ON tblbuilding.buildingpk = tblrooms.buildingfk)
INNER JOIN (tblcustomer
INNER JOIN tblfacilitymgr
ON tblcustomer.customerpk =
tblfacilitymgr.customerfk)
ON tblbuilding.buildingpk = tblfacilitymgr.buildingfk)
LEFT JOIN (tblcabinet
LEFT JOIN tblequipment
ON tblcabinet.cabinetpk = tblequipment.cabinetfk)
ON tblrooms.roomspk = tblcabinet.roomsfk
UNION
SELECT tblcustomer.organizationfk,
tblcustomer.shopnamefk,
tblcustomer.officesymfk,
tblcustomer.lastname,
tblcustomer.firstname,
tblrooms.buildingfk,
tblrooms.roomspk,
tblbuilding.buildingname,
tblrooms.roomname,
tblcabinet.cabinetname,
tblequipment.cabinetfk,
tblequipment.equipmentnamefk,
tblequipment.equipmentbrandfk,
tblequipment.equipmentnetworktypefk
FROM ((tblbuilding
INNER JOIN tblrooms
ON tblbuilding.buildingpk = tblrooms.buildingfk)
LEFT JOIN (tblcabinet
LEFT JOIN tblequipment
ON tblcabinet.cabinetpk = tblequipment.cabinetfk)
ON tblrooms.roomspk = tblcabinet.roomsfk)
INNER JOIN (tblcustomer
INNER JOIN tblroomspoc
ON tblcustomer.customerpk = tblroomspoc.customerfk)
ON tblrooms.roomspk = tblroomspoc.roomsfk;
The search form looks like this:
Search Form
The code for cmdsearch is here:
Option Compare Database
Option Explicit 'always set this It will point out errors with field/vaiable names
Private Sub cboSearchLastName_AfterUpdate()
Me.cboSearchFirstName.Requery
End Sub
Private Sub cboSearchOrganization_AfterUpdate()
Me.cboSearchShopName.Requery
End Sub
Private Sub cboSearchShopName_AfterUpdate()
Me.cboSearchOfficeSym.Requery
End Sub
Private Sub cmdReset_Click()
Me.cboSearchBuildingName = ""
Me.cboSearchRoomName = ""
Me.cboSearchOrganization = ""
Me.cboSearchShopName = ""
Me.cboSearchOfficeSym = ""
Me.cboSearchLastName = ""
Me.cboSearchFirstName = ""
Me.FilterOn = False
End Sub
Private Sub txtBuildingID_AfterUpdate()
Me.lstFacilityMgr.Requery
End Sub
Private Sub txtRoomsID_AfterUpdate()
Me.lstRoomsPOC.Requery
End Sub
Private Sub cmdSearch_Click()
Dim strWhere As String
Dim lngLen As Long
Dim startStr As String
If Not IsNullOrEmpty(Me.cboSearchLastName) Then
startStr = IIf(strWhere = "", "", " AND ")
strWhere = strWhere & startStr & "[LastName] ='" & Me.cboSearchLastName & "'"
End If
If Not IsNullOrEmpty(Me.cboSearchFirstName) Then
startStr = IIf(strWhere = "", "", " AND ")
strWhere = strWhere & startStr & "[FirstName] ='" & Me.cboSearchFirstName & "'"
End If
If Not IsNullOrEmpty(Me.cboSearchOrganization) Then
startStr = IIf(strWhere = "", "", " AND ")
strWhere = strWhere & startStr & "[OrganizationFK] =" & Me.cboSearchOrganization
End If
If Not IsNullOrEmpty(Me.cboSearchShopName) Then
startStr = IIf(strWhere = "", "", " AND ")
strWhere = strWhere & startStr & "[ShopNameFK] =" & Me.cboSearchShopName
End If
If Not IsNullOrEmpty(Me.cboSearchOfficeSym) Then
startStr = IIf(strWhere = "", "", " AND ")
strWhere = strWhere & startStr & "[OfficeSymFK] =" & Me.cboSearchOfficeSym
End If
If Not IsNullOrEmpty(Me.cboSearchBuildingName) Then
startStr = IIf(strWhere = "", "", " AND ")
strWhere = strWhere & startStr & "[BuildingFK] =" & Me.cboSearchBuildingName
End If
If Not IsNullOrEmpty(Me.cboSearchRoomName) Then
startStr = IIf(strWhere = "", "", " AND ")
strWhere = strWhere & startStr & "[RoomsPK] =" & Me.cboSearchRoomName
End If
If Not IsNullOrEmpty(Me.cboSearchEquipmentName) Then
startStr = IIf(strWhere = "", "", " AND ")
strWhere = strWhere & startStr & "[EquipmentNameFK] =" & Me.cboSearchEquipmentName
End If
If Not IsNullOrEmpty(Me.cboSearchEquipmentSerialNo) Then
startStr = IIf(strWhere = "", "", " AND ")
strWhere = strWhere & startStr & "[SerialNoFK] =" & Me.cboSearchEquipmentSerialNo
End If
Call MsgBox(strWhere, vbOKOnly, "Debug")
lngLen = Len(strWhere) - 5
If lngLen <= 0 Then
MsgBox "No criteria", vbInformation, "Nothing to do."
Else
'strWhere = Left$(strWhere, lngLen)
MsgBox strWhere
If DCount("*", "qryRecordSet", strWhere) = 0 Then
MsgBox "No corresponding records to your search criteria." & vbCrLf & vbCrLf
Me.FilterOn = False
Me.cboSearchBuildingName = ""
Me.cboSearchRoomName = ""
Me.cboSearchOrganization = ""
Me.cboSearchShopName = ""
Me.cboSearchOfficeSym = ""
Me.cboSearchLastName = ""
Me.cboSearchFirstName = ""
Else
Me.Filter = strWhere
Me.FilterOn = True
End If
End If
End Sub
Function IsNullOrEmpty(val As Variant) As Boolean
'First conditional validates for Nothing
'Second condition validates for an Empty String situation "" or " "
Dim ret As Boolean: ret = False
If IsMissing(val) Then
ret = True
ElseIf (val Is Nothing) Then
ret = True
ElseIf (val & vbNullString = vbNullString) Then
ret = True
ElseIf (Len(Trim(val)) <= 0) Then
ret = True
End If
IsNullOrEmpty = ret
End Function
My search form works perfectly. The problem I'm having is that some searches returns duplicate results. This is because the union query contains duplicate results. I do not know of a way to produce a query which contains all the info I need, and not make duplicate results. Because, one customer can be the facility manager for multiple buildings, one building can have multiple facility managers. One customer can be the point of contact for multiple rooms, one room can have multiple POCs. Equipment can only be in one room.
To clarify, if Building "A" , room "1100" has three POCs then if I search for building A, room 1100 I see three results. I need to only see one result.
I have two text boxes on my form (hidden so user doesn't see them). txtBuildingID and txtRoomsID. Everything else on the form requeries based on those two text boxes. I need the combination of those two text boxes to be unique. That is because, if I search for only building "A" and building A has three rooms, I should see Building ID 1 / Room ID 1... Building ID 1 / Room ID 2, etc.
The reason for this is because I want to filter using multiple criteria, but display only a unique building id / room id. This is because if I search for "Smith" and he is the POC for building A, Room 1100, I want to see that building / room and all information about that room. Because, if smith doesn't answer his phone, I can call "Jones".
I do not care which record gets deleted, so long as I have unique records between the two text boxes. I don't know enough about SQL, but from what little I know I don't think this can be done with SQL. I think I need to use perhaps DCount to count the records and then remove duplicates. I have no idea how to do this. I've spent days on google, I haven't even come close to a solution. At best, if I ever get the syntax right I can count the number of duplicates (more than 1 unique record between buildingfk and roomspk), but then I'm not sure how to delete duplicates. Or if I need to specify which duplicate to delete. Personally as long as they are deleted, I don't care.
I asked a friend of mine who is very good w/ programming, and it stumped him. He advised I ask here. So I really appreciate your help here.
Query
I'm making some progress.
I've been able to successfully count the number of records.
The code I use is here:
If DCount("*", "qryRecordSet", "BuildingFK = " & Me.txtBuildingID & " And RoomsPK = " & Me.txtRoomsID > 1) Then
MsgBox "There are duplicates!" & vbCrLf & vbCrLf
'Code to remove duplicate records here
End If
The MsgBox is only for troubleshooting purposes. But I have tested it and confirmed it works. Now, I need to apply this to the form filter, somehow. That would be Me.Filter. Currently, that is Me.Filter = strWhere.
Basically, I need to further filter out strWhere so there are no more duplicates. How do i do that?

If Then Else on 2 separate recordsets

I need to test 2 different conditions on 2 separate recordsets. I am not good with VBA, I have a very basic code, I just need help with If Then syntax. Here is my Code:
Private Sub SaveRecord_Click()
'**** add a new record ****
Dim db As Database, rs1 As Recordset, rs2 As Recordset
Set db = CurrentDb
Set rs1 = db.OpenRecordset("ExpAsset", DB_OPEN_DYNASET)
Set rs2 = db.OpenRecordset("LogTest", DB_OPEN_DYNASET)
'**** Following code is updating the tables in the ExpAsset table with new information from the form****
If rs1.NoMatch Then
rs1.AddNew
rs1("User") = Me!Location
rs1("Type") = Me!Type
rs1("Model") = Me!MODEL
rs1("Asset_ID") = Me!Asset_ID
rs1("Serial_Number") = Me!Serial
rs1.Update
Else
MsgBox "Serial Number: " & Me!Serial & " already exists.", 48, "ERROR!"
Me!Serial.SetFocus
End If
'**** Following code is creating a log in Logtest table with information provided in the form****
If rs2.NoMatch Then
rs2.AddNew
rs2("Asset_Type") = Me!Type
rs2("Transfer_Type") = "New purchase"
rs2("Description") = Me!DESCRIPTION
rs2("DELIVERED_TO") = Me!Location
rs2("DELIVERED_BY") = Me!DeliveredBy
rs2("RECEIVED_BY") = Me!Receiver
rs2("RECEIVED_DATE") = Me!Date
rs2.Update
MsgBox "Part information has been updated in the database!"
'clear the controls to add more customers
Call ClearControls
Else
MsgBox "Asset ID: " & Me!Asset_ID & " already exists.", 48, "ERROR!"
Me!Asset_ID.SetFocus
End If
rs1.Close
rs2.Close
db.Close
End Sub
I know The If Then Else syntax is incorrect, I need to check both conditions, serial no. and asset ID.
Check the Access online help topic for Recordset.NoMatch Property:
Indicates whether a particular record was found by using the Seek method or one of the Find methods (Microsoft Access workspaces only).
However in your code, you're opening a recordset but not using either seek or find. In that situation, you haven't asked to match anything, so .NoMatch will be False every time. The logic is similar to this ...
If rs1.NoMatch Then
' this code will never run
Else
' this code runs every time
End If
You can use DCount to determine whether ExpAsset contains a given Asset_ID value.
DCount("*", "ExpAsset", "Asset_ID = " & Me!Asset_ID) ' if Asset_ID is numeric
DCount("*", "ExpAsset", "Asset_ID = '" & Me!Asset_ID & "'") ' if Asset_ID is text
Once you have a working DCount expression, you can use logic like this ...
If DCount("*", "ExpAsset", "Asset_ID = " & Me!Asset_ID) = 0 Then
' Asset_ID not present in table -> add it
Else
' inform user Asset_ID already present in table
End If
You are right HansUp, my code was silly, I realised later after I had posted that there was no criteria to test against. Following is the right code, I tested it and it works :)
Private Sub SaveRecord_Click()
'**** add a new record ****
Dim db As Database, rs1 As Recordset, rs2 As Recordset, Criteria As String, Criteria2 As String
Set db = CurrentDb
Set rs1 = db.OpenRecordset("ExpAsset", DB_OPEN_DYNASET)
Set rs2 = db.OpenRecordset("LogTest", DB_OPEN_DYNASET)
Criteria = "[serial_number]='" & Me!Serial & "'"
Criteria2 = "[Asset_ID]='" & Me!Asset_ID & "'"
'**** Following code is updating the tables in the ExpAsset table with new information from the form****
rs1.FindFirst Criteria
If rs1.NoMatch Then
rs1.FindFirst Criteria2
If rs1.NoMatch Then
rs1.AddNew
rs1("User") = Me!Location
rs1("Type") = Me!Type
rs1("Model") = Me!MODEL
rs1("Asset_ID") = Me!Asset_ID
rs1("Serial_Number") = Me!Serial
rs1.Update
'**** Following code is creating a log in Logtest table with information provided in the form****
rs2.AddNew
rs2("Asset_Type") = Me!Type
rs2("Transfer_Type") = "New purchase"
rs2("Description") = Me!DESCRIPTION
rs2("DELIVERED_TO") = Me!Location
rs2("DELIVERED_BY") = Me!DeliveredBy
rs2("RECEIVED_BY") = Me!Receiver
rs2("RECEIVED_DATE") = Me!Date
rs2.Update
MsgBox "Part information has been updated in the database!"
'clear the controls to add more customers
Call ClearControls
Else
MsgBox "Asset_ID: " & Me!Asset_ID & " already exists.", 48, "ERROR!"
Me!Asset_ID.SetFocus
End If
Else
MsgBox "Serial Number: " & Me!Serial & " already exists.", 48, "ERROR!"
Me!Serial.SetFocus
End If
rs1.Close
rs2.Close
db.Close
End Sub