Access 2013 - Set a field value based on value of another field - vba

I have a combo box (Status) which includes the following:
Shortage
Allocated
Actioned
Acknowledged
Complete
I also have 5 other date fields which are as follows:
Shortage_date
Allocated_date
Actioned_date
Acknowledged_date
Complete_date
However I want this status to be populated automatically based on what data has been entered in my previous fields.
For example, once shortage_date has been populated with a valid date (00/00/0000) I want the "status" to change to "shortage".
Once allocated_date has been populated with a valid date (00/00/0000) I want the "status" to change to "allocated".
I saw this bit of code online but I'm totally confused:
Private Sub Textbox1_AfterUpdate()
If Textbox1.Value = "1" Then
Textbox2.Value = "10"
End If
End Sub
I believe mine should look something like this but I dont know what I need to make sure it validates the date.
Private Sub shortage_date_AfterUpdate()
If shortage_date.Value = "(I want to valididate the date here)" Then
Status.Value = "Status"
End If
End Sub
Hope I make sense!

Firstly, I would set up an Input Mask on the field itself. You can do that by putting the form into design view, then select the field, then go the Property Sheet which isAlt+Enter if it isn't open, then select the Data tab and set up a Input Mask. That will handle your validation part so you don't have to in code.
Then you should be able to just use the code:
Private Sub shortage_date_AfterUpdate()
If Nz(shortage_date.Value, "") <> "" Then
Status.Value = "Status"
End If
End Sub
The If statement is just to make sure that it doesn't reset the value back to the original every time the date is changed. Also here is link where you can read about Input Masks: https://msdn.microsoft.com/en-us/library/office/ff821336.aspx
Update: Changed to Input Mask instead of Validation Rule

Related

MS Access refresh form and keep position on screen [duplicate]

This should be an easy one. This form is filtered by [Dismissed] = "N". When the user clicks the "Dismiss" button, the [Dismissed] field changes to "Y". After the requery, the form should then return to the same row where the user was previously at.
Private Sub DismissButton_Click()
Me!Dismissed = "Y"
MsgBox "Dismissed!", vbOKOnly
Dim GoBackToThisRecord As Integer
GobacktothisRecord = Me.CurrentRecord
Me.Requery
Set Me.CurrentRecord=GoBackToThisRecord
End Sub
However, even though the built-in help files say that CurrentRecord is a read/write property, I get an "Invalid use of property" error message on this last line.
After setting the [Dismiss]="Y", and requerying the form, how do I get the user back to his/her previous location in the form?
I don't understand how your solution can work if the form is filtered to a value that the edited record no longer matches -- if you're filtered on [Dismissed] = "N" then changing the current record's Dismissed field to Y should cause the requeried form to exclude the record you've just updated.
That aside, I would never do it the way you've done it, as Me.CurrentRecord returns a number representing the position in the record. Since a requery can cause the number of records to change (e.g., somebody else edits or adds or deletes a record causing it to be included/excluded from the form's recordset) and the position of the sought-for record to change, I would use the PK instead.
Dim lngPK as Long
lngPK = Me!MyPKID
Me.Requery
With Me.RecordsetClone
.FindFirst "[MyPKID]=" & lngPK
If Not .NoMatch Then
If Me.Dirty Then
Me.Dirty = False
End If
Me.Bookmark = .Bookmark
End If
End With
That won't deal with the filter issue, but I leave that aside, since it didn't seem to be the issue that I thought it would be from the description of the original problem.
Nevermind. Fixed it myself. The last line is now:
Me.Recordset.Move GoBackToThisRecord
The right way to move to the previous record, whether it is a new one or not, is
Me.Recordset.Move GoBackToThisRecord -1
I use this function:
Public Sub RequeryFormAndKeepCurrentlySelectedRecord(f As Form)
Dim Position As Long
Position = f.CurrentRecord
f.Requery
If Position > 1 Then
f.Recordset.move Position - 1
End If
End Sub

Change AllowEdits property based on Entry Date

I have number of split forms in an Access 2016 database which are regularly used by various employees for data entry. It is important that users are able to see old records but are not able to edit them.
However, I want to allow users to edit records that have been made that day in case they notice an error in a record they have just entered.
My current approach is to set the AllowEdits property on the form to yes, then to override it for entries made on the same day with the following code
Private Sub Form_Load()
If (Me![rec_date] < Now()) Then
Me.AllowEdits = False
Else: Me.AllowEdits = True
End If
End Sub
I think there is a problem with the If criteria though, as all this currently does is prevent editing of all records.
For background [rec_date] refers to the date on which the record was entered.
Couple of things:
Use the "Current" event instead if you're working with record changes. Form Load only works when the form itself opens. If you change records it will do nothing for you.
Might as well move that Else statement down to the next line and indent correctly for readability.
Your conditional statement doesn't quite match what you told me. You're trying to match a specific day but you use a date time (now()) instead of date. You also use less than instead of equals. I would suggest using equals and the date function (note: doesn't use () and returns only the date portion of now() ).
Hopefully that helps! Here's my suggested code:
Private Sub Form_Current()
' Only allow editing of records created today.
If (Me![rec_date] = Date) Then
Me.AllowEdits = True
Else
Me.AllowEdits = False
End If
End Sub
An even shorter form as suggested by Mat's Mug
Private Sub Form_Current()
Me.AllowEdits = Me![rec_date] = Date ' Only allow editing of records created today.
End Sub

MS Word Document Form - Check Value of Text Form Field on Exit

I'm creating a Form in Microsoft Word. I have several 'Text form fields' some of which I want to restrict so users can only enter numbers. I don't understand why Microsoft gives you the option to change the 'Type' to 'Number' when that still allows any value to be input. Since that seems to be the case I have turned to VBA.
I'm trying to run a macro when the user exits one of these fields, to make sure the input is valid. I would rather not create a new macro for each field I want to restrict to numeric.
I think my problem is that I don't know how to get the result of the current field. I could create a different macro for each field, and get the result by specifying its name explicitly, but it seems like a smarter way would exist.
Here's what I have so far.
Sub validateNumericFields()
'Check to see if the value in the current field is numeric
'If it is not, send a message to the user, and set value to default value
If IsNumeric(Selection.Fields(1).Result) = False Then
MsgBox "You must enter a valid number.", vbExclamation
Selection.Fields(1).Result = Selection.Fields(1).TextInput.Default
End If
End Sub
There are various ways to get the "name" of a form field, since this is also a bookmark. The FormField object does have a Name property, but I can't get to it from the Selection object available when OnExit runs. But I can get the bookmark name, so:
Sub validateNumericFields()
'Check to see if the value in the current field is numeric
'If it is not, send a message to the user, and set value to default value
Dim ff As word.FormField
Set ff = ActiveDocument.FormFields(Selection.Bookmarks(1).Name)
If IsNumeric(ff.Result) = False Then
MsgBox "You must enter a valid number.", vbExclamation
ff.Result = ff.TextInput.Default
End If
End Sub

Validating entered values in DataGridView Cell using VB.Net

I'm using VB.Net 2008 and trying to validate a certain cell with certain values like:
In DataGridView1 i want to check the entered data in column 1 and cell 1 if it's less than 10 or not so i used the following code
Private Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
If DataGridView1.CurrentCell.ColumnIndex = 1 Then
If DataGridView1.Rows(e.RowIndex).Cells(1).Value < 10 Then
DataGridView1.Rows(e.RowIndex).ErrorText = "Not Less Than 10"
e.Cancel = True
End If
End If
End Sub
The problem is: every time i try to enter any value in this cell it see nothing (Empty Value) unless if it was already has a value before i start to edit it and always use this value regardless of any new value i write
so how do i validate those cells to not allow users to leave this cell unless it get the right value
Note : CellValidated is working perfectly but it has no e.cancel to prevent users from leaving this cell
I know this is old, but in order to validate the actual value you need to use DataGridView1.Rows(e.RowIndex).Cells(1).FormattedValue, which will give you the modified value. By using DataGridView1.Rows(e.RowIndex).Cells(1).Value you will always get the previous value (uneditted, if the cell is editted for the first time you will get the empty value you see). Note that the FormattedValue works only in the CellValidating method.
Hope this helps anyone who passes by this question. ^^

Changing Textbox.DefaultValue in Access

I would like to be able to change the Textbox.DefaultValue during the 'On Load' event of a form such that each time the form is loaded the user is prompted with an InputBox to change a specific TextBox.Default value which in my case the TextBox control on the table is called Stream. I have tried the following code but each time it gives me a
'RunTime Error 3422 Cannot modify table structure. Another user has
the table open'.
Private Sub Form_Load()
CurrentDb.TableDefs("Class 1 Students (C1)").Fields("Stream").DefaultValue = InputBox("Enter Stream Letter:")
End Sub
I am using Microsoft Access
As Doug Glancy said in a comment, don't change the field's default value in table design. Instead change the text box's default value.
This is a critical point in a multi-user database application --- you wouldn't want one user stomping on another's default value choice. But, even if this will always be a single-user application, changing the table design means you can't have the table open in the record source of your form.
Changing the text box default value is easy. I added an unbound text box, txtDefaultStream, to my form's header. And, in its after update event, I change Me.txtStream.DefaultValue. The code is below.
Here is a screenshot of that form in action. I had A as the default when entering the first 2 rows. Then entered B in the default stream text box. Notice the new record has B in its Stream text box.
Private Sub txtDefaultStream_AfterUpdate()
Dim strDefault As String
If Len(Trim(Me.txtDefaultStream & vbNullString)) > 0 Then
strDefault = """" & Me.txtDefaultStream.value & """"
Me.txtStream.DefaultValue = strDefault
Else
Me.txtStream.DefaultValue = vbNullString
End If
End Sub
As Doug Glancy said, use the textbox, so you should try
Private Sub Form_Load()
Me.AText.DefaultValue = "='S'"
End Sub