How to create a comment box with time and date stamp in Access using VBA - vba

Completely new to VBA and need help with detailed instructions (dummy version for me).
I have a table with various columns and the following columns, specifically:
ReviewerComments
NewComment
I created a form with both of these fields and need to create an Append Comment button that moves the text from NewComment field and appends it to ReviewerComment field and time/date stamps the comments as they are added. I named this button cmdAppendComment.
I had seen someone else post something and I tried, but as I am completely new to this I know I messed it up. Any help is greatly appreciated.
This is what the VBA code looks like right now:
Private Sub cmdAppendComment_Click()
If (IsNull(NewComment.Value)) Then
MsgBox ("Please provide a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
If (IsNull(ReviewerComments.Value)) Then
ReviewerComments.Value = NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
Else
ReviewerComments.Value = ReviewerComments.Value & _
vbNewLine & vbNewLine & _
NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
End If
NewComment.Value = ""
End Sub

I have some suggestions for your code:
1. Do not check if a textbox is null but how many characters your textbox has. You should always do it that way because otherwise you tend to get errors.
If (len(Me.NewComment.Value & "") > 0) Then
MsgBox ("Please provide a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
Here you check the length of the string in your textbox. You need to append "" because otherwise you tend to get null-errors or something similar.
2. You forgot to reference the objects in your form correctly. You have your form and in that form you put your textboxes and also your VBA-code. Your can reference all your objects with "Me.[FormObjects]".
The compiler complains that "NewComment.Value" or "ReviewerComment.Value" is not initialized or in other words not dimensioned. With correct reference this should stop.
Private Sub cmdAppendComment_Click()
If (len(Me.NewComment.Value & "") > 0) Then
MsgBox ("Please provide a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
If (IsNull(Me.ReviewerComments.Value)) Then
Me.ReviewerComments.Value = Me.NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
Else
Me.ReviewerComments.Value = Me.ReviewerComments.Value & _
vbNewLine & vbNewLine & _
Me.NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
End If
Me.NewComment.Value = ""
End Sub

Related

Prevent data duplication with condition

I want to setup a data duplication check on a text box which is used to input serial numbers.
If the entered serial number is already found in the database, it should call a MsgBox to alert the user before clearing the value in the text box.
However, if the entered serial number contains "RW", the check should be disabled.
Private Sub Serial_Number_AfterUpdate()
Dim NewSerialNumber As String
Dim stLinkCriteria As String
NewSerialNumber = Me.Serial_Number.Value
stLinkCriteria = "[Serial_Number] = " & "'" & NewSerialNumber & "'"
If Me.Serial_Number = DLookup("[Serial_Number]", "Esagon_End", stLinkCriteria) Then
MsgBox "This serial number, " & NewSerialNumber & ", has already been entered into the database." _
& vbCr & vbCr & "Please check the serial number again.", vbI, "Duplicate information"
Me.Undo
End If
End Sub
If this cannot be done with VBA I'm open to other methods like queries. Thank you.
Looking at what you have asked, I think this is what you are looking for. If it isn't then leave a comment and I'll try to update my answer.
Private Sub Serial_Number_AfterUpdate()
'If it doesn't contain "RW"
If InStr(Me.Serial_Number, "RW") = 0 Then
'If serial number not in the database
If DCount("*", "Esagon_End", "Serial_Number = '" & Me.Serial_Number & "'") > 0 Then
'Alert user and blank the text box
Call MsgBox("The serial number " & Me.Serial_Number & " is already in the database." _
& vbCrLf & vbCrLf & "Please check the serial number you are entering.", _
vbInformation, "Duplicate Serial")
Me.Serial_Number = ""
End If
End If
End Sub

VBA at Access - Filter with several criteria, where one criteria can be Null

I got some problems with my vba code.
I got a form at access with a filter.
At the moment the one filter is for start/end date and a Person.
And because i am a noob, there is an other Filter for a cost centre and the start/end date.
I want to combine both, but with the case, cost centre can be Null or not.
My "main" filter looks like this:
Private Sub Befehl51_Click()
If Nz(Me.txtvon, "") = "" Then //StartDate
MsgBox "Bitte Datumsbereich wählen!"
Exit Sub
End If
If Nz(Me.txtbis, "") = "" Then //EndDate
MsgBox "Bitte Datumsbereich wählen!"
Exit Sub
End If
Me.Filter = "[TaetigkeitsDatum] between " & Format(Nz(Me!txtvon, Date),"\#yyyy-mm-dd\#") & "
and " & Format(Nz(Me!txtbis, Date), "\#yyyy-mm-dd\#") & " And " & "[PersonalID] = " & Me.Liste0 & ""
Me.FilterOn = True
End Sub
The syntax for the cost criteria is like:
[TaetigkeitsKostenstellenIDRef] = "Kombinationsfeld145"
Thanks for help!
You're nearly there, there are just some minor SQL syntax errors.
I've written it to separate lines to increase readability and make understanding easier
Me.Filter = "[TaetigkeitsDatum] BETWEEN " & Format(Nz(Me!txtvon, Date),"\#yyyy-mm-dd\#") & " AND " & Format(Nz(Me!txtbis, Date), "\#yyyy-mm-dd\#") & _
" AND [PersonalID] = " & Me.Liste0
If IsNumeric(Me!Kombinationsfeld145) Then
Me.Filter = Me.Filter & " AND [TaetigkeitsKostenstellenIDRef] =" & Me!Kombinationsfeld145
End If
Some of the changes I've made:
Spacing was off. Before every And and variable name, there should be a space.
The " & " between And and a variable name was unnecessary, removed that.
I've only included the comparison on Me!Kombinationsfeld145 if it's numeric. That way, if it's Null or a zero-length string, it's not included in the comparison.

Word in message box appears in a different line

I use the following VBA to open a message box:
Sub Message()
MsgBox ("Do you want create a file on your desktop?" _
& vbCr & " " _
& vbCr & "Once you click yes an unprotected file with all sheets visible will be saved on your desktop and opened. You can immediately start working with this file.")
End Sub
All this works fine.
However, as you can see in the screenshot the word "file" goes in a different line. Is it possible to format the messagebox or change the VBA code so the word "file" does not appear in a different line?
It depends on the resolution of the PC of the user. In my case I even get it like this:
If you want to control the lines, then you should write a custom form. There you would have much better control over the display, and if you play a bit with its properties, you would mimic exactly the MsgBox():
Some sample code, Label1 is a label element:
Private Sub UserForm_Initialize()
Me.Label1 = "Do you want create a file on your desktop?" _
& vbCr & " " _
& vbCr & "Once you click yes an unprotected file with all sheets visible will be saved on your desktop and opened." & _
vbCrLf & "You can immediately start working with this file."
End Sub
Perhaps adjust your code with line breaks to suit. For example:
Sub Message()
MsgBox ("Do you want create a file on your desktop?" _
& vbCr & " " _
& vbCr & "Once you click yes an unprotected file" _
& vbCr & " " _
& vbCr & "with all sheets visible will be saved on your desktop and opened." _
& vbCr & " " _
& vbCr & "You can immediately start working with this file.")
End Sub

Add title and change format to 2 decimals places of msgbox output

Would need to add a title and change the ouput decimal places (2 decimal) of below code but i am with problems doing it. Can you help? Thanks a lot
Sub msgAlert()
MsgBox "First Response Time (hours)= " & _
Worksheets("Parsing").Range("H21").Value & _
vbCrLf & "Investigation Time (hours)= " & _
Worksheets("Parsing").Range("I21").Value & _
Format(dTotalArea, "&#,##0")
End Sub
To add a title to a message box, use it like this:
Msgbox "My message",,"My title"
To get two decimal places, use this format:
Format(dTotalArea,"0.00")
Use a dot (.) as a decimal separator, even if your regional settings would require using a comma (,).
So your code would look like this:
Sub msgAlert()
MsgBox "First Response Time (hours)= " & _
Worksheets("Parsing").Range("H21").Value & _
vbCrLf & "Investigation Time (hours)= " & _
Worksheets("Parsing").Range("I21").Value & _
Format(dTotalArea, "0.00"),,"This is the title"
End Sub
Let me know if this works. :)

RecordSource in Access SQL

I have a form which allows the user to view all records with the LinkRef field equal to a specified value and also either the Clearance Applying For or Clearance Level a certain value.
LinkRef is a user ID which is pulled in using OpenArgs from the previous form. The code for the form_load I have presently is:
Private Sub Form_Load()
'MsgBox Me.OpenArgs
Me.C_LinKRef = Me.OpenArgs
Me.chbToggleEdit.Value = False
'MsgBox Me.C_LinKRef
Dim mySQL As String
mySQL = _
"Select * " & _
"From TabClearDetail " & _
"Where (C_LinKRef = " & Me.C_LinKRef & ") " & _
"And ([Clearance Applying For] = 'BPSS' " & _
"Or [Clearance Applying For] = 'BPSS (EDF)' " & _
"Or [Clearance Applying For] = 'BPSS (Magn)' " & _
"Or [Clearance Applying For] = 'BPSS (Sella)' " & _
"Or [Clearance Applying For] = 'BPSS Equiv' " & _
"Or C_ClearanceLevel = 'BPSS' " & _
"Or C_ClearanceLevel = 'BPSS (EDF)' " & _
"Or C_ClearanceLevel = 'BPSS (Magn)' " & _
"Or C_ClearanceLevel = 'BPSS (Sella)' " & _
"Or C_ClearanceLevel = 'BPSS Equiv' " & _
"Or C_ClearanceLevel = 'DESTROYED' " & _
"Or C_ClearanceLevel = 'Lapsed' " & _
"Or C_ClearanceLevel = 'NOT_FLWDUP' " & _
"Or C_ClearanceLevel = 'NOT_SPECIFIED' " & _
"Or C_ClearanceLevel = 'Refused' " & _
"Or C_ClearanceLevel = 'Withdrawn');"
Me.RecordSource = mySQL
'MsgBox Me.RecordsetClone.RecordCount
End Sub
mySQL seems to behave as it should when there are matching records. But sometimes there won't be any records because the specified person doesn't have any of these clearance levels and hasn't applied for them, then I would like the form to come up blank or a message to appear saying that there is no matching records.
Presently though if there is no matching records the form will pull in the LinkRef but fill all the other text boxes with values from a completely different record (it seems to be the last record I viewed). Not to sure how to remedy this, I tried to use the RecordsetClone.RecordCount to say if it is equal to 0 then msgbox, but it seems to late to do that as it always seems to find at least 1 entry, as even if there should be 0 it has already populated the textboxes with data from another field so 1 is found.
The LinkRef textbox is populated from OpenArgs. All other textboxes are populated using a query which looks in the TabClearDetail table and pulls the values in. I'm starting to think I'd be better either just using Queries or just using Code, but I wasn't sure how to use OpenArgs in a query and for some things it's so much quicker to make a query than code.
Here is the code for my save dialog I refer to in reply to #Roland post. This code is called in the Form_Close() sub.
Private Sub SaveDialog()
Dim Msg, Style, Title As String
Dim Response As Integer
Msg = "Would you like to save your changes?"
Style = vbYesNoCancel
Title = "Save Changes"
On Error GoTo Err_BackFromAddBPSSButton_Click
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
'DoCmd.Close
DoCmd.OpenForm ("Basic Personal Information")
Else
If Response = vbNo Then
Me.Undo
'DoCmd.Close
DoCmd.OpenForm ("Basic Personal Information")
End If
End If
Exit_BackFromAddBPSSButton_Click:
Exit Sub
Err_BackFromAddBPSSButton_Click:
MsgBox Err.Description
Resume Exit_BackFromAddBPSSButton_Click
End Sub
Apologies for the very wordy question, hopefully all the detail is necessary and it makes sense, any suggestions HUGELY appreciated!
Try changing the order of events:
Don't set the TextBox value first. Pass the OpenArgs to the mySql string. With mySql open a recordset in VBA (OpenRecordset) and do a RecordCount. If it is zero then set the Recordsource to SELECT * FROM TabClearDetail WHERE 1=2 . Else set mySQl as the Recordsource (or pass the Recordset). Only then set the TextBox and CheckBox.
Private Sub Form_Load()
Dim i as Integer
i = Me.OpenArgs
Dim mySQL As String
mySQL = _
"Select * " & _
"From TabClearDetail " & _
"Where (C_LinKRef = " & Me.C_LinKRef & ") " & _
"And ([Clearance Applying For] IN ('BPSS','BPSS (EDF)','BPSS (Magn)','BPSS Sella)','BPSS Equiv') " & _
"Or C_ClearanceLevel IN ('BPSS','BPSS (EDF)','BPSS (Magn)','BPSS (Sella)','BPSS Equiv','DESTROYED','Lapsed','NOT_FLWDUP','NOT_SPECIFIED','Refused','Withdrawn'));"
Dim rst as Recordset
Set rst = CurrentDB.OpenRecordset(mySQL)
rst.MoveLast
rst.MoveFirst
If rst.RecordCount = 0 then
Me.RecordSource = "SELECT * FROM TabClearDetail WHERE 1=2"
Me.C_LinKRef = ""
Me.chbToggleEdit.Value = False
Else
Me.RecordSource = mySQL
Me.C_LinKRef = i
Me.chbToggleEdit.Value = False
End If
rst.Close
Set rst = Nothing
End Sub
Sorry, cannot test it here so may be a little buggy. If any problems I will check tomorrow
Using a query and passing [Forms]![BPSS Clearance].[OpenArgs] into that as well as the conditions on C_ClearanceLevel and Clearance Applying For has worked for me. No idea why the code didn't work because in theory it's doing the same thing, but I've got a solution so I'm happy. Thanks for all the suggestions