Saltar al contenido principal

¿Cómo registrar la fecha y la hora automáticamente cuando cambia la celda?

Es fácil para nosotros insertar una fecha y hora estáticas manualmente o insertar una fecha dinámica que cambia con la hora del sistema con una fórmula. Si desea registrar la fecha y la hora automáticamente cuando cambia o ingresa valores, este problema puede ser algo diferente de resolver. Pero, en este artículo, puede resolver esta tarea con los siguientes pasos.

Registre la fecha y la hora automáticamente cuando la celda cambie con el código VBA


flecha azul burbuja derecha Registre la fecha y la hora automáticamente cuando la celda cambie con el código VBA

Por ejemplo, tengo un rango de valores, y ahora, cuando cambio o escribo nuevos valores en la Columna B, quiero que se registre automáticamente la fecha y hora actuales en la Columna C como se muestra en la siguiente captura de pantalla:

doc-actualización-tiempo-valor-cambios-1

Puede finalizar esta tarea con el siguiente código VBA. Por favor haz lo siguiente:

1. Mantenga pulsado el ALT + F11 teclas para abrir el Ventana de Microsoft Visual Basic para Aplicaciones.

2. Luego elija su hoja de trabajo usada de la izquierda Proyecto Explorer, haga doble clic en él para abrir el Módulo, y luego copie y pegue el siguiente código VBA en el Módulo en blanco:

Código VBA: registra la fecha y la hora automáticamente cuando cambia la celda

Private Sub Worksheet_Change(ByVal Target As Range)
'Update 20140722
Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.ActiveSheet.Range("B:B"), Target)
xOffsetColumn = 1
If Not WorkRng Is Nothing Then
    Application.EnableEvents = False
    For Each Rng In WorkRng
        If Not VBA.IsEmpty(Rng.Value) Then
            Rng.Offset(0, xOffsetColumn).Value = Now
            Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy, hh:mm:ss"
        Else
            Rng.Offset(0, xOffsetColumn).ClearContents
        End If
    Next
    Application.EnableEvents = True
End If
End Sub

doc-actualización-tiempo-valor-cambios-1

3. Luego guarde y cierre este código para regresar a la hoja de trabajo, ahora cuando cambie el valor de la celda o escriba nuevos datos en la Columna B, la fecha y la hora se registrarán automáticamente en la Columna C.

Notas:

1. En el código anterior, puede modificar el "CAMA Y DESAYUNO”A cualquier otra columna en la que desee cambiar los valores de celda en este script: Establecer WorkRng = Intersect (Application.ActiveSheet.Range ("B: B"), Target).

2. Con esto xColumnaDesplazamiento = 1 script, puede insertar y actualizar la fecha y la hora en la primera columna junto a la columna de valor cambiante, puede cambiar el número 1 a otros números, como 2,3,4,5 ... eso significa que la fecha se insertará el segunda, tercera, cuarta o quinta columna además de la columna de valores modificados.

3. Cuando elimina un valor en la columna modificada, la fecha y la hora también se eliminarán.

Las mejores herramientas de productividad de oficina

🤖 Asistente de IA de Kutools: Revolucionar el análisis de datos basado en: Ejecución inteligente   |  Generar codigo  |  Crear fórmulas personalizadas  |  Analizar datos y generar gráficos  |  Invocar funciones de Kutools...
Características populares: Buscar, resaltar o identificar duplicados   |  Eliminar filas en blanco   |  Combine columnas o celdas sin perder datos   |   Ronda sin fórmula ...
Super búsqueda: Búsqueda virtual de criterios múltiples    Búsqueda V de valores múltiples  |   VLookup en varias hojas   |   Búsqueda difusa ....
Lista desplegable avanzada: Crear rápidamente una lista desplegable   |  Lista desplegable dependiente   |  Lista desplegable de selección múltiple ....
Administrador de columnas: Agregar un número específico de columnas  |  Mover columnas  |  Toggle Estado de visibilidad de columnas ocultas  |  Comparar rangos y columnas ...
Características destacadas: Enfoque de cuadrícula   |  Vista de diseño   |   Gran barra de fórmulas    Administrador de hojas y libros de trabajo   |  Biblioteca de Recursos (Texto automático)   |  Selector de fechas   |  Combinar hojas de trabajo   |  Cifrar/descifrar celdas    Enviar correos electrónicos por lista   |  Súper filtro   |   Filtro especial (filtro negrita/cursiva/tachado...) ...
Los 15 mejores conjuntos de herramientas12 Texto Herramientas (Añadir texto, Quitar caracteres, ...)   |   50+ Tabla Tipos (Diagrama de Gantt, ...)   |   40+ Práctico Fórmulas (Calcular la edad según el cumpleaños, ...)   |   19 Inserción Herramientas (Insertar código QR, Insertar imagen desde la ruta, ...)   |   12 Conversión Herramientas (Números a palabras, Conversión de Moneda, ...)   |   7 Fusionar y dividir Herramientas (Filas combinadas avanzadas, Células partidas, ...)   |   ... y más

Mejore sus habilidades de Excel con Kutools for Excel y experimente la eficiencia como nunca antes. Kutools for Excel ofrece más de 300 funciones avanzadas para aumentar la productividad y ahorrar tiempo.  Haga clic aquí para obtener la función que más necesita...

Descripción


Office Tab lleva la interfaz con pestañas a Office y hace que su trabajo sea mucho más fácil

  • Habilite la edición y lectura con pestañas en Word, Excel, PowerPoint, Publisher, Access, Visio y Project.
  • Abra y cree varios documentos en nuevas pestañas de la misma ventana, en lugar de en nuevas ventanas.
  • ¡Aumenta su productividad en un 50% y reduce cientos de clics del mouse todos los días!
Comments (109)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hi,
Is it is also possible to have a VBA code that is able to create a timestamp for cells that have a formula in it? So when the value changes (changes from empty cell to a cell with a value >0 in it) the timestamp appears?
Kind regards,
Femke
This comment was minimized by the moderator on the site
Hello, Femke,
To solve your problem, please apply the below VBA code:
Private Sub Worksheet_Change(ByVal Target As Range)
'Updateby ExtendOffice
Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
Dim xDRg As Range

On Error Resume Next
Set xDRg = Target.DirectDependents

If Not xDRg Is Nothing Then

Set WorkRng = Intersect(Application.ActiveSheet.Range("B:B"), xDRg)

xOffsetColumn = 1
If Not WorkRng Is Nothing Then
    Application.EnableEvents = False
    For Each Rng In WorkRng
        If Not VBA.IsEmpty(Rng.Value) Then
            Rng.Offset(0, xOffsetColumn).Value = Now
            Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy, hh:mm:ss"
        Else
            Rng.Offset(0, xOffsetColumn).ClearContents
        End If
    Next
    Application.EnableEvents = True
End If
Else
Set WorkRng = Intersect(Application.ActiveSheet.Range("B:B"), Target)
xOffsetColumn = 1
If Not WorkRng Is Nothing Then
    Application.EnableEvents = False
    For Each Rng In WorkRng
        If Not VBA.IsEmpty(Rng.Value) Then
            Rng.Offset(0, xOffsetColumn).Value = Now
            Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy, hh:mm:ss"
        Else
            Rng.Offset(0, xOffsetColumn).ClearContents
        End If
    Next
    Application.EnableEvents = True
End If

End If
End Sub


Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Sir ! I have a problem that I have data entering Column B in sheet 1 and Date Column C in sheet 2....please guide me what will be the code for that...Anyone
This comment was minimized by the moderator on the site
I want to use this code to update multiple cells within the same sheet. How do I write this?For example, when cell C12 changes, C13 gets the datewhen cell C26 changes, C27 gets the date
when cell G13 changes, G14 gets the date
and so on
This comment was minimized by the moderator on the site
datetime    auto_cycle    tool    time_difference
01-01-2021 :10:10:09    1    1    00:00:11
03-01-2021 :10:10:20    1    2    00:00:02
13-10-2021 :10:10:22    1    3    00:00:04
13-10-2021 :10:10:26    1    4    00:00:04
13-10-2021 :10:10:30    1    5    00:00:06
13-10-2021 :10:10:36    1    6    00:00:02
13-10-2021 :10:10:38    1    7    00:00:05
13-10-2021 :10:10:43    1    8    00:00:00
13-10-2021 :10:10:43    1    9    00:00:06
13-10-2021 :10:10:49    1    10    00:00:03
13-10-2021 :10:10:52    1    11    00:00:08
13-10-2021 :10:11:00    1    13    00:00:10
13-10-2021 :10:11:10    1    12    00:00:04
13-10-2021 :10:11:14    1    14    00:00:05
13-10-2021 :10:11:19    1    16    00:00:04
13-10-2021 :10:11:23    1    17    00:00:04
13-10-2021 :10:11:27    1    18    00:00:02
13-10-2021 :10:11:29    1    19    00:00:04
13-10-2021 :10:11:33    1    20    00:00:05
13-10-2021 :10:11:38    1    21    00:00:07
13-10-2021 :10:11:45    1    12    

this is my master file suppose i change the time value in a column corresponding time difference sshould be update in d column automatically without trigger the macro assigning button could you please help me out 
This comment was minimized by the moderator on the site
I see a couple of people asking about formulas and I'm sorry if I missed the answer somewhere in the thread. I am updating very large data sets that then are migrated to hidden sheets. I have those sheets each set with this "latest update" code but since everything on those sheets references back to the larger data set, it does not see a cell update as the formulas remain the same even thought the values change. I need it to update when the value changes and not jus when the content of the cell changes.
This comment was minimized by the moderator on the site
Sir ! Did you find solution of your problem then please share it with me.I am also facing the same issue...I am new in this...Please
This comment was minimized by the moderator on the site
Private Sub Worksheet_Change(ByVal Target As Range)
'Update 20140722
Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.ActiveSheet.Range("A:A"), Target)
xOffsetColumn = 1
If Not WorkRng Is Nothing Then
Application.EnableEvents = False
For Each Rng In WorkRng
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Now
Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy, hh:mm:ss"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
Application.EnableEvents = True
End If
End Sub

This comment was minimized by the moderator on the site
1 26-02-2021, 11:32:49
1 26-02-2021, 11:32:49
1 26-02-2021, 11:32:49
1 26-02-2021, 11:32:49
1 26-02-2021, 11:32:50
1 26-02-2021, 11:32:50
1 26-02-2021, 11:32:50
1 26-02-2021, 11:32:50
1 26-02-2021, 11:32:50
0 26-02-2021, 11:33:04
0 26-02-2021, 11:33:04
0 26-02-2021, 11:33:04
0 26-02-2021, 11:33:04
0 26-02-2021, 11:33:04
0 26-02-2021, 11:33:04
0 26-02-2021, 11:33:04
0 26-02-2021, 11:33:04
0 26-02-2021, 11:33:04
0 26-02-2021, 11:33:04

Why on 0 value its getting date.. when cell have data then only get date otherwise show balnk...how we can do it vba code
This comment was minimized by the moderator on the site
Hi,The code works perfect but if changed the data in A i was wondering if i could have the date in column B and the time in Column D?Thanks for any help.
This comment was minimized by the moderator on the site
Private Sub Worksheet_Change(ByVal Target As Range)
'Update 20140722
Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.ActiveSheet.Range("J:J"), Target)
xOffsetColumn = 1
If Not WorkRng Is Nothing Then
Application.EnableEvents = False
For Each Rng In WorkRng
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Now
Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy, hh:mm:ss"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
Application.EnableEvents = True
End If
xOffsetColumn = 2
If Not WorkRng Is Nothing Then
Application.EnableEvents = False
For Each Rng In WorkRng
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Now
Rng.Offset(0, xOffsetColumn).NumberFormat = "hh:mm:ss"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
Application.EnableEvents = True
End If
End Sub
This comment was minimized by the moderator on the site
Hi,If i were to have 2 columns duplicating the same macros, how can that be possible.
I want to show the date and time in column B for values changed in A; while also wanting to show the time and date in column D for values changed in C.
This comment was minimized by the moderator on the site
Hi Extend Office, thank you for guiding me.I am a beginner , i had this problem which i saw some of your faced. This was the situationFor e.g
You want your date and time shown in Column A when any other column of the same row B:AZ for example got their values changed.So heres my solution. Please correct me if the code has any issues. TIA.
Private Sub Worksheet_Change(ByVal Target As Range)

Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.ActiveSheet.Range("B:AZ"), Target)'B:AZ put your own columns'rownumber=Activecell.Row will not work because it it will locate the adjacent row after you press enter or when ur mouse click on other cells
rownumber = Target.Row
If Not WorkRng Is Nothing Then
Application.EnableEvents = False
For Each Rng In WorkRng
If Not VBA.IsEmpty(Rng.Value) Then
Range("A" & rownumber).Value = Now 'gives A and the adjacent row number
Range("A" & rownumber).NumberFormat = "dd-mm-yyyy, hh:mm:ss"
End If
Next
Application.EnableEvents = True
End If
End Sub



Thank you.
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations