I am creating a form template in Excel that has Cell B = TODAY() so, when a user opens the template to fill out the form, today's date is displayed.
However, once the user fills out the form, I would like Cell B to equal the value of TODAY(), so the cell does not update every time the Workbook is opened.
My solution to this was to create a Macro that does the following:
When the user clicks on Cell A, a cell that the user is required to fill in with text, Cell B, containing the formula =TODAY(), is copied and pasted as a value to the same position. Then, Cell A is selected again so the user can fill in the required information.
Below is my example VBA, which checks if Cell A is empty instead of being clicked on. I would like to change this though, if someone could help with that.
In this example, Cell A is E11 and Cell B is E13.
Sub Date_Change(ByVal Target As Range)
Dim Rng As Range
Set Rng = Sheets("Form").Range("E13")
If Sheets("Form").Range("E11") = Empty Then
Sheets("Form").Range("E13") = TODAY()
Else
Rng.Copy
Rng.PasteSpecial xlPasteValues
Set Rng = Nothing
Application.CutCopyMode = False
Cells(11, 5).Select
End Sub
How's this (this goes in the worksheet you want to run it on's module):
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cellA As Range, cellB As Range
Set cellA = Sheets("Form").Range("E11")
Set cellB = Sheets("Form").Range("E13")
If Target.Row = cellA.Row And Target.Column = cellA.Column Then
Dim Rng As Range
Set Rng = cellA
If cellA = Empty Then
cellB.Value = WorksheetFunction.Text(Month(Now()) & "/" & Day(Now()) & "/" & Year(Now()), "MM/DD/YYYY")
Else
Rng.Copy
Rng.PasteSpecial xlPasteValues
Set Rng = Nothing
Application.CutCopyMode = False
Cells(11, 5).Select
End If
End If
End Sub
You may need to check my declarations, but that should get you going. It'll check to see if cell E11 was selected, and if so, will run.
Within the workbook object you have a built in event workbook_beforesave... you could put the code there.
I recorded a macro which updates B3 to be a hard value, eliminating the formula.
I then copied the code out of the macro and hit save. You may need to update the "range" to account for specific worksheet if multiple sheets in workbook.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Range("B3").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.