I have an Access macro in a form that I only want to run on a blank record. How do I check to see if a record has been saved. The Me.dirty property doesn't work for me because it checks to see if a saved record have been altered or modified.
Private Sub FIND_MEMBER_AfterUpdate()
Me.FIRST_NAME = DLookup("[FIRST_NAME]", "CM_ROSTER", "[SOC_SEC_NUM] = '" & Me.SOC_SEC_NUM & "'")
Me.MID_INIT = DLookup("[MID_INIT]", "CM_ROSTER", "[SOC_SEC_NUM] = '" & Me.SOC_SEC_NUM & "'")
Me.LAST_NAME = DLookup("[LAST_NAME]", "CM_ROSTER", "[SOC_SEC_NUM] = '" & Me.SOC_SEC_NUM & "'")
End Sub
I may have a solution:
Private Sub FIND_MEMBER_AfterUpdate()
If Me.NewRecord = True Then
Me.FIRST_NAME = DLookup("[FIRST_NAME]", "CM_ROSTER", "[SOC_SEC_NUM] = '" & Me.SOC_SEC_NUM & "'")
Me.MID_INIT = DLookup("[MID_INIT]", "CM_ROSTER", "[SOC_SEC_NUM] = '" & Me.SOC_SEC_NUM & "'")
Me.LAST_NAME = DLookup("[LAST_NAME]", "CM_ROSTER", "[SOC_SEC_NUM] = '" & Me.SOC_SEC_NUM & "'")
Else
GoTo exit_sub
End If
exit_sub:
End Sub
It sounds like the property you are looking for is the form's .NewRecord property, which is true until a new record is saved.
Related
I have a form with information about how long the citizens have lived in which state and city.I have txt boxes to give time range. I have comboboxes where I can select cities according to the selected state or states (Multiple Selection Options). And I have a report generation button that uses these filters.
Function searchCriteria() As String 'Filtering with City and State
Dim strFilter, strCriteria, strSQL As String
Select Case cmb_State Case Is = ""
If Me.cmb_City = "<Multi Selection>" Then
strCriteria = "[City] in (" & TempVars!TempMultiCity & ")"
Else
strCriteria = "[City] ='" & Me.cmb_City & "'"
End If
Case Is = "<Multi Selection>"
If IsLbUsed(Me.lbKSALL) = True Then
If IsNull(Me.cmb_City) Or Me.cmb_City = "" Then
strCriteria = "[State] in (" & TempVars!TempMultiState & ")"
ElseIf Me.cmb_City = "<Multi Selection>" Then
If IsLbUsed(Me.lbKTALL) = True Then
strCriteria = "[City] in (" & TempVars!TempMultiCity & ")"
Else
strCriteria = "[State] in (" & TempVars!TempMultiState & ")"
End If
Else
strCriteria = "[City] ='" & Me.cmb_City & "'"
End If
Else
strCriteria = "[City] ='" & Me.cmb_City & "'"
End If
Case Else
If IsNull(Me.cmb_City) Or Me.cmb_City = "" Then
strCriteria = "[State]='" & Me.cmb_State & "'"
ElseIf Me.cmb_City = "<Multi Selection>" Then
strCriteria = "[City] in (" & TempVars!TempMultiCity & ")"
Else strCriteria = "[State]='" & Me.cmb_State & "'"
strCriteria = strCriteria & " AND [City] ='" & Me.cmb_City & "'"
End If
End Select
searchCriteria = strCriteria
End Function
===========================================================================================
Sub search() ' Applies function searchcriteria and gets the datas from query
Dim strCriteria As String
strCriteria = searchCriteria()
strSQL = "select * from qryForForm where(" & strCriteria & ")"
Me.RecordSource = strSQL
Me.Requery
End Sub
======================================================================================
Private Sub cmd_ReportAll_Click() ' applies all filter that I used in my Form
Dim strCriteria As String
If IsNull(Me.txtFrom) Or IsNull(Me.txtTo) Then ' txt boxes for time range filter
strCriteria = searchCriteria()
DoCmd.OpenReport "All", acViewPreview, , strCriteria
Else
strCriteria = searchCriteria()
DoCmd.OpenReport "All", acViewPreview, , strCriteria & " And [LivingDate] Between #" & Format(Me.txtFrom, "yyyy\/mm\/dd") & "# And #" & Format(Me.txtTo, "yyyy\/mm\/dd") & "#"
End If
Call search
End Sub
The problem is: if I want to generate a report without selecting state and city (both are not being selected), it doesn't show any data. How can I solve this?
I have this split form with some basic search functions based on comboboxes and search fields. Now I want to exclude the records where my checkbox chk_NonC = false.
The VBA-code I currently use to filter my record source qry_Administration:
Function SearchCriteria()
Dim Customer, CustomerLocation, CustomerLocationPlace, ExecutionDate, Material As String
Dim Intern, Extern As String
Dim task, strCriteria As String
If Me.chk_AuditEX = True Then
Extern = "[AuditEX] = " & Me.chk_AuditEX
Else
Extern = "[AuditEX] like '*'"
End If
If Me.chk_AuditIN = True Then
Intern = "[AuditIN] = " & Me.chk_AuditIN
Else
Intern = "[AuditIN] like '*'"
End If
If IsNull(Me.cbo_CustomerLocations) Then
CustomerLocation = "[CustomerLocationID] like '*'"
CustomerLocationPlace = "[LocationCompanyPlace] like '*'"
Else
CustomerLocation = "[LocationCompanyName] = '" & Me.cbo_CustomerLocations.Column(0) & "'"
CustomerLocationPlace = "[LocationCompanyPlace] = '" & Me.cbo_CustomerLocations.Column(1) & "'"
End If
If IsNull(Me.cbo_Customers) Then
Customer = "[CustomerID] like '*'"
Else
Customer = "[CustomerID] = " & Me.cbo_Customers
End If
If IsNull(Me.txt_ExecutionDateTo) Then
ExecutionDate = "[ExecutionDate] like '*'"
Else
If IsNull(Me.txt_ExecutionDateFrom) Then
ExecutionDate = "[ExecutionDate] like '" & Me.txt_ExecutionDateTo & "'"
Else
ExecutionDate = "([ExecutionDate] >= #" & Format(Me.txt_ExecutionDateFrom, "mm/dd/yyyy") & "# And [ExecutionDate] <= #" & Format(Me.txt_ExecutionDateTo, "mm/dd/yyyy") & "#)"
End If
End If
If IsNull(Me.cbo_Material) Or Me.cbo_Material = "" Then
Material = "[MaterialID] like '*'"
ElseIf Me.cbo_Material = 6 Then
Material = "[MaterialID] in (" & TempVars!tempMaterial & ")"
Else
Material = "([MaterialID] = " & Me.cbo_Material & ")"
End If
strCriteria = Customer & "And" & CustomerLocation & "And" & CustomerLocationPlace & "And" & _
& ExecutionDate & Material & "And" & Extern & "And" & Intern
task = "Select * from qry_Administration where (" & strCriteria & ") order by ExecutionDate DESC"
Debug.Print (task)
Me.Form.RecordSource = task
Me.Form.Requery
End Function
Now I want to add this new checkbox Non-Compliant named chk_NonC
When I set chk_NonC to true and press search I want my split-form to show all records.
When I set chk_NonC to false and press search I want my split-form to hide all records where Non_compliant is true
You can see it as a hide function for my database. If I set this checkbox to false then hide all records where non-compliant is set to true.
Please note that function SearchCriteria is called on the OnChange Events of the comboboxes or by clicking a search-icon on the top of my split-form.
Just follow the same flow defined for the other controls.
Create the string portion for the compliance and append it to the rest of the sql script.
Dim strCompliant As String
strCompliant = IIf(Me.chk_NonC,"[Non_compliant]=True","[Non_compliant]=False")
strCriteria = Customer & " And " [...] & " And " & strCompliant
Keep in mind, you need spaces between the " And " joins in strCriteria.
basically what i want is when change the status and update it will change the color of that updated cell
here is my code:
Private Sub Btnupdate_Click(sender As Object, e As EventArgs) Handles btnupdate.Click
Try
Dim datePublish As String = Format(dtpDatePublish.Value, "yyyy-MM-dd")
If txtAccessionNo.Text = "" Or txtAuthor.Text = "" Or txtTitle.Text = "" Or TxtBoxISBN.Text = "" Or txtPublisher.Text = "" Or CBSection.Text = "" Or TxtBoxSubject.Text = "" Or TxtBoxYearPub.Text = "" Or TxtBoxShelf.Text = "" Or TxtBoxCallNumber.Text = "" Then
MsgBox("All fields are required to be filled up.", MsgBoxStyle.Exclamation)
Else
sql = "SELECT * FROM `books` WHERE `AccessionNo` = '" & txtAccessionNo.Text & "'"
reloadtxt(sql)
If dt.Rows.Count > 0 Then
panelstatus.Visible = True
sqledit = "UPDATE `books` SET `Isbn`='" & TxtBoxISBN.Text & "',
`BookSection` = '" & CBSection.SelectedItem & "', `Subject` = '" & TxtBoxSubject.Text & "', `Title` = '" & txtTitle.Text & "',
`Author` = '" & txtAuthor.Text & "', `JointAuthor` = '" & txtjointauthor.Text & "', `Publisher` = '" & txtPublisher.Text & "',
`YearPublish` = '" & TxtBoxYearPub.Text & "', `Edition` = '" & TxtBoxEdition.Text & "', `Volume` = '" & TxtBoxVolume.Text & "',
`Aquistion` = '" & CBAquisition.SelectedItem & "', `DateAquired` = '" & datePublish & "', `SponsorPrice` = '" & TxtBoxPrice.Text & "',
`Shelf` = '" & TxtBoxShelf.Text & "', `CallNumber` = '" & TxtBoxCallNumber.Text & "', `Remarks` = '" & TxtBoxRemarks.Text & "', `Status` = '" & CBstatus.SelectedItem & "' WHERE `AccessionNo` = '" & txtAccessionNo.Text & "'"
save_or_update(sql, sqladd, sqledit, "Books has been updated in the database.", "New books has been saved in the database.")
Call InventoryAdd_Load(sender, e)
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
here is my cell formatting code
Private Sub DtgList1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dtgList1.CellFormatting
For Each row As DataGridViewRow In dtgList1.Rows
If row.Cells(17).Value = "Available" Then
row.DefaultCellStyle.ForeColor = Color.White
row.DefaultCellStyle.ForeColor = Color.Red
End If
Next
End Sub
When adding row colours to DataGridViews, I normally handle the Paint event. The error 'Conversion from string "Available" to type 'Double' is not valid suggests that row.Cells(17).Value is a Double, not a string. Are you sure that's the correct column?
From your code, I'm guessing your column is called 'Status'. If not, rename below as needed, or continue to use column number but ensure it's the correct column. As you are using Select * to populate your table, I'd suggest using a Column Name is more reliable as column order may change or new columns added to the database in future.
Private Sub dtgList1_Paint(sender As Object, e As PaintEventArgs) Handles dtgList1.Paint
For Each rw As DataGridViewRow In dtgList1.Rows
If rw.Cells("Status").Value = "Available" Then
rw.DefaultCellStyle.ForeColor = Color.White
Else
rw.DefaultCellStyle.ForeColor = Color.Red
End If
Next
End Sub
I posted about this last week, but my wedding was at the end of the week, so I've been away for the past 5 days, so I'm trying again to see if I can get some help.
A lot of people have asked me why I'm not using a bound form, I tried that and couldn't get it to do what I wanted. I am new to Access and VBA in general, so the extent of my knowledge is following YouTube tutorials, but by all means if someone can walk me through how to create the bound form and everything, I'll take your advice.
Essentially I have a table with the data and then I want a form that has a text box for each field in the table with a subtable of the main table incorporated into the form. The user fills in the text boxes with the information and then either adds it to the table or they can click on a record and edit it or delete it with the corresponding buttons on the form.
I was having some issues with some syntax and recently fixed that today, so now I'm finally fine tuning stuff on my form. The only issue I'm having now is that if there is already a record in the table, the form won't insert a new record once I click the add button. I fill the text boxes in and click the 'Add' button and the form refreshes like the add command worked, but then the new record doesn't show up in the table. However if I go back to the table and delete any record that is already in the table and then go back to the form and fill the boxes in again and click the 'Add' button, then a new record is inserted into the form.
I created a database before the one I'm currently working on and it works fine. It is very similar to the database that I'm working on now, so I just copied it and then renamed the fields and text boxes and everything to match the information that this database will be handling.
Any ideas what's going on here and how I could fix?
Here's a link to some screenshots of the database: https://imgur.com/a/QvCY2
Here's my code:
Option Compare Database
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtICN.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO tblInventory(ICN, manu, model, serial, descr, dateRec, dateRem, dispo, flgDispo, project, AMCA, UL, comments) " & _
" VALUES(" & Me.txtICN & ", '" & Me.txtManu & "', '" & Me.txtModel & "', '" & Me.txtSerial & "', '" & Me.txtDescr & "', '" & Me.txtDateRec & "', '" & Me.txtDateRem & "', '" & Me.txtDispo & "', '" & Me.chkFlg & "', '" & Me.txtProject & "', '" & Me.txtAMCA & "', '" & Me.txtUL & "', '" & Me.txtComments & "')"
Else
'otherwise (Tag of txtICN stores the ICN of item to be modified)
CurrentDb.Execute "UPDATE tblInventory " & _
" SET ICN = " & Me.txtICN & _
", manu = '" & Me.txtManu & "'" & _
", model = '" & Me.txtModel & "'" & _
", serial = '" & Me.txtSerial & "'" & _
", descr = '" & Me.txtDescr & "'" & _
", dateRec = '" & Me.txtDateRec & "'" & _
", dateRem = '" & Me.txtDateRem & "'" & _
", dispo = '" & Me.txtDispo & "'" & _
", flgDispo = '" & Me.chkFlg & "'" & _
", project = '" & Me.txtProject & "'" & _
", AMCA = '" & Me.txtAMCA & "'" & _
", UL = '" & Me.txtUL & "'" & _
", comments = '" & Me.txtComments & "'" & _
" WHERE ICN = " & Me.txtICN.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
frmInventorySub.Form.Requery
End Sub
Private Sub cmdClear_Click()
Me.txtICN = ""
Me.txtManu = ""
Me.txtModel = ""
Me.txtSerial = ""
Me.txtDescr = ""
Me.txtDateRec = ""
Me.txtDateRem = ""
Me.txtDispo = ""
Me.chkFlg = ""
Me.txtProject = ""
Me.txtAMCA = ""
Me.txtUL = ""
Me.txtComments = ""
'focus on ID text box
Me.txtICN.SetFocus
'set button edit to enable
Me.cmdEdit.Enabled = True
'change caption of button add to Add
Me.cmdAdd.Caption = "Add"
'clear tag on txtICN for reset new
Me.txtICN.Tag = ""
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Private Sub cmdDelete_Click()
'delete record
'check existing selected record
If Not (Me.frmInventorySub.Form.Recordset.EOF And Me.frmInventorySub.Form.Recordset.BOF) Then
'confirm delete
If MsgBox("Are you sure you want to delete this item?", vbYesNo) = vbYes Then
'delete now
CurrentDb.Execute "DELETE FROM tblInventory " & _
"WHERE ICN =" & Me.frmInventorySub.Form.Recordset.Fields("ICN")
'refresh data in list
Me.frmInventorySub.Form.Requery
End If
End If
End Sub
Private Sub cmdEdit_Click()
'check whether there exists data in list
If Not (Me.frmInventorySub.Form.Recordset.EOF And Me.frmInventorySub.Form.Recordset.BOF) Then
'get data to text box control
With Me.frmInventorySub.Form.Recordset
Me.txtICN = .Fields("ICN")
Me.txtManu = .Fields("manu")
Me.txtModel = .Fields("model")
Me.txtSerial = .Fields("serial")
Me.txtDescr = .Fields("descr")
Me.txtDateRec = .Fields("dateRec")
Me.txtDateRem = .Fields("dateRem")
Me.txtDispo = .Fields("dispo")
Me.chkFlg = .Fields("flgDispo")
Me.txtProject = .Fields("project")
Me.txtAMCA = .Fields("AMCA")
Me.txtUL = .Fields("UL")
Me.txtComments = .Fields("comments")
'store id of item in Tag of txtICN in case ICN is modified
Me.txtICN.Tag = .Fields("ICN")
'change caption of button add to Update
Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
I have limited experience with Access. I followed some YouTube tutorials and made a functioning DB a couple of months ago.
I adapted the first DB, which essentially is changing the field names in the table in the Access file.
I can't get the new DB to function. I have a form with a subtable of the main table and it has a few text fields to fill in with the information to input. Then it has a few buttons to the side that either Add to the table, Delete from the table, Clear the text fields, Close the form, Edit a selected field, and then the Add button changes to Update after you Edit a field so that you can click Update to update the selected field after you've made changes to it.
All of this works in my first DB and in theory it should work exactly the same after changing the field names in the new DB and the corresponding txt field names and so on. I am having a tough time getting it to work for Add, Update, or Delete.
The error on the Add is Run time error "3134" Syntax error in INSERT INTO statement.
The Update and Delete error is run time error '3061' Too few parameters. expected 1.
The Clear works, as well as the Close and Edit.
Here is the code:
Option Compare Database
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtICN.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO tblInventory(ICN, manu, modelNum, serialNum, descr, dateRec, projectNum, dispo, flgDispo, dateRemoved, comments)" & _
" VALUES(" & Me.txtICN & ", '" & Me.txtManu & "', '" & Me.txtModel & "', '" & Me.txtSerial & "', '" & Me.txtDescrip & "', '" & Me.txtDateRec & "', '" & Me.txtProjectNum & "', '" & Me.txtDispo & "', '" & Me.chkFlag & "', '" & Me.txtDateRemoved & "', '" & Me.txtComments & "')"
Else
'otherwise (Tag of txtICN store the Lab Inventory Control Number to be modified)
CurrentDb.Execute "UPDATE tblInventory " & _
" SET ICN = " & Me.txtICN & _
", manu = '" & Me.txtManu & "'" & _
", modelNum = '" & Me.txtModel & "'" & _
", serialNum = '" & Me.txtSerial & "'" & _
", descr = '" & Me.txtDescrip & "'" & _
", dateRec = '" & Me.txtDateRec & "'" & _
", projectNum = '" & Me.txtProjectNum & "'" & _
", dispo = '" & Me.txtDispo & "'" & _
", flgDispo = '" & Me.chkFlag & "'" & _
", dateRemoved = '" & Me.txtDateRemoved & "'" & _
", comments = '" & Me.txtComments & "'" & _
" WHERE ICN = " & Me.txtICN.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
tblInventorySub.Form.Requery
End Sub
Private Sub cmdClear_Click()
Me.txtICN = ""
Me.txtManu = ""
Me.txtModel = ""
Me.txtSerial = ""
Me.txtDescrip = ""
Me.txtDateRec = ""
Me.txtProjectNum = ""
Me.txtDispo = ""
Me.chkFlag = ""
Me.txtDateRemoved = ""
Me.txtComments = ""
'focus on ICN text box
Me.txtICN.SetFocus
'set button edit to enable
Me.cmdEdit.Enabled = True
'change caption of button add to Add
Me.cmdAdd.Caption = "Add"
'clear tag on txtICN for reset new
Me.txtICN.Tag = ""
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Private Sub cmdDelete_Click()
'delete record
'check existing selected record
If Not (Me.tblInventorySub.Form.Recordset.EOF And Me.tblInventorySub.Form.Recordset.BOF) Then
'confirm delete
If MsgBox("Are you sure you want to delete this inventory entry?", vbYesNo) = vbYes Then
'delete now
CurrentDb.Execute "DELETE FROM tblInventory " & _
"WHERE ICN = " & Me.tblInventorySub.Form.Recordset.Fields("ICN")
'refresh data in list
Me.tblInventorySub.Form.Requery
End If
End If
End Sub
Private Sub cmdEdit_Click()
'check whether there exists data in list
If Not (Me.tblInventorySub.Form.Recordset.EOF And Me.tblInventorySub.Form.Recordset.BOF) Then
'get data to text box control
With Me.tblInventorySub.Form.Recordset
Me.txtICN = .Fields("ICN")
Me.txtManu = .Fields("manu")
Me.txtModel = .Fields("modelNum")
Me.txtSerial = .Fields("serialNum")
Me.txtDescrip = .Fields("descr")
Me.txtDateRec = .Fields("dateRec")
Me.txtProjectNum = .Fields("projectNum")
Me.txtDispo = .Fields("dispo")
Me.chkFlag = .Fields("flgDispo")
Me.txtDateRemoved = .Fields("dateRemoved")
Me.txtComments = .Fields("comments")
'store ICN in Tag of txtICN in case id is modified
Me.txtICN.Tag = .Fields("ICN")
'change caption of button add to Update
Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
What data types are dateRec, flgDispo, dateRemoved? Values for DateTime fields must be delimited with # not '. Is flgDispo a Yes/No type? If so, this is numeric type field and number values do not have delimiters.
Why delete records? Do you really want to lose history? Why not just flag as 'Archived' or 'Inactive'? Deleting records should be a rare event.
I always give subform containers a name different from the object they hold, like ctrInventory:
CurrentDb.Execute "DELETE FROM tblInventory WHERE ICN = " & Me.ctrInventory!ICN
First, all your date expressions must be formatted like this:
", dateRec = #" & Format(Me.txtDateRec.Value, "yyyy\/mm\/dd") & "#" & _
or you could apply my CSql function to handle all this:
Convert a value of any type to its string representation
However, it appears that you could make life much easier for yourself by simply binding your form to the table - and then remove all of this code as the form will handle edit, insert, and delete automatically.