Saltar al contenido principal

¿Cómo insertar la marca de tiempo actual cuando los datos en otra celda cambian en Excel?

Supongamos que recibe una hoja de trabajo que necesita que modifique los datos en una determinada columna. Y después de modificar la hoja de trabajo, debe insertar la marca de tiempo modificada para que otros sepan qué celdas se han cambiado. ¿Como lidiar con? Este artículo le mostrará el método para insertar la marca de tiempo actual cuando los datos en otra celda cambian en Excel como se muestra a continuación.

Inserte la marca de tiempo actual cuando los datos en otra celda cambien con el código VBA


Inserte la marca de tiempo actual cuando los datos en otra celda cambien con el código VBA

Como se muestra en la siguiente captura de pantalla, debe completar la marca de tiempo en la columna E si se cambian las celdas correspondientes en la columna C. Haz lo siguiente.

1. En la hoja de trabajo necesita modificar y marcar con marca de tiempo, haga clic con el botón derecho en la pestaña de la hoja y luego haga clic en Ver código desde el menú contextual.

2. Luego copie y pegue el siguiente código VBA en el Código ventana del Microsoft Visual Basic para aplicaciones ventana. Ver captura de pantalla:

Código de VBA: inserte la marca de tiempo actual cuando cambien los datos en otra celda

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20180830
Dim xCellColumn As Integer
Dim xTimeColumn As Integer
Dim xRow, xCol As Integer
Dim xDPRg, xRg As Range
xCellColumn = 3
xTimeColumn = 5
xRow = Target.Row
xCol = Target.Column
If Target.Text <> "" Then
    If xCol = xCellColumn Then
       Cells(xRow, xTimeColumn) = Now()
    Else
        On Error Resume Next
        Set xDPRg = Target.Dependents
        For Each xRg In xDPRg
            If xRg.Column = xCellColumn Then
                Cells(xRg.Row, xTimeColumn) = Now()
            End If
        Next
    End If
End If
End Sub

Note: En el código, el número 3 significa que va a modificar los datos en la columna C, y el 5 indica que la marca de tiempo se completará en la columna E. Cámbiela según sus necesidades.

3. presione el otro + Q llaves para cerrar el Microsoft Visual Basic para aplicaciones ventana.

De ahora en adelante, al cambiar los datos en la columna C, la marca de tiempo se completará en las celdas correspondientes en la columna E, como se muestra a continuación.

Propina. Selector de fechas. Insertar la fecha utilidad de Kutools for Excel le ayuda a insertar rápidamente la fecha con el formato de fecha especificado en una celda seleccionada.
¡Descárgalo y pruébalo ahora! (Pista gratuita de 30 días)


Artículos relacionados:

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 (60)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hallo!

Der VBA-Code funktioniert wunderbar. Gibt es eine Möglichkeit den Code zu erweitern?

Jetzt gerade sie der Coade wie folgt aus:

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20180830
Dim xCellColumn As Integer
Dim xTimeColumn As Integer
Dim xRow, xCol As Integer
Dim xDPRg, xRg As Range
xCellColumn = 10
xTimeColumn = 16
xRow = Target.Row
xCol = Target.Column
If Target.Text <> "" Then
If xCol = xCellColumn Then
Cells(xRow, xTimeColumn) = Now()
Else
On Error Resume Next
Set xDPRg = Target.Dependents
For Each xRg In xDPRg
If xRg.Column = xCellColumn Then
Cells(xRg.Row, xTimeColumn) = Now()
End If
Next
End If
End If
End Sub

Allerdings möchte ich gerne, dass ein Zeitstempel auch dann ausgegeben wird, wenn in Spalte 3, 4, 6, 8, 10 oder 13 eine Änderung erfolgt. WElche Änderung spielt keine Rolle, nur das es eine gab. Geht das?

Liebe Grüße
Paolo :-)
This comment was minimized by the moderator on the site
Hi OP,

Not sure if you are still seeing this. I am trying to update this so that the formula picks up a range. I want Col E:I to be updated with a timestamp if Col J:N update to "Completed". Do you have the code for that?

Thanks,
Huzefa A.
This comment was minimized by the moderator on the site
Hi Huzefa,

I don't know if I understand your question clearly. The following VBA code may help. Please give it a try.
The relationship is a 1:1 mapping between the columns. With this script, when a cell in column J is updated to "Completed", the timestamp will be inserted into the corresponding cell in column E. Similarly, updates to column K will affect column F, and so on.

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20230816
    Dim IntersectRng As Range
    Dim TargetColumn As Integer

    ' Check if the changed cell is in columns J to N
    Set IntersectRng = Application.Intersect(Target, Me.Range("J:N"))

    If Not IntersectRng Is Nothing Then
        For Each cell In IntersectRng
            ' If the changed cell's value is "Completed"
            If cell.Value = "Completed" Then
                ' Calculate the target column in E:I
                TargetColumn = cell.Column - 5
                Me.Cells(cell.Row, TargetColumn).Value = Now()
            End If
        Next cell
    End If
End Sub
This comment was minimized by the moderator on the site
How would I go about running this Macro in all of the sheets in my workbook? It is only working in the first sheet.
This comment was minimized by the moderator on the site
Hi Jon,
The following VBA code can help. Please give it a try.
Note: This VBA code needs to be added to the ThisWorkbook (Code) window.
https://www.extendoffice.com/images/stories/comments/comment-picture-zxm/Thisworkbook.png
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'Updated by Extendoffice 20221208
Dim xCellColumn As Integer
Dim xTimeColumn As Integer
Dim xRow, xCol As Integer
Dim xDPRg, xRg As Range
xCellColumn = 3
xTimeColumn = 5
xRow = Target.Row
xCol = Target.Column
If Target.Text <> "" Then
    If xCol = xCellColumn Then
       Cells(xRow, xTimeColumn) = Now()
    Else
        On Error Resume Next
        Set xDPRg = Target.Dependents
        For Each xRg In xDPRg
            If xRg.Column = xCellColumn Then
                Cells(xRg.Row, xTimeColumn) = Now()
            End If
        Next
    End If
End If
End Sub
This comment was minimized by the moderator on the site
Hallo !
Ich habe noch eine Frage zu dem oben angegebenen VBA-Code.
Bei meiner Tabelle befindet sich der Wert, für den der Zeitstempel erstellt werden soll in Spalte G.
Der Wert in G errechnet sich aus der Summe der Werte in den Spalten K:AA.
Die Werte in K:AA ergeben sich aus einem anderen Tabellenblatt, unter Benutzung der Zählenwenn-Funktion.
Wenn die Werte direkt in K:AA eingegeben werden aktualisiert sich der Zeitstempel wie gewünscht.
Wenn die Werte in K:AA durch "Zählenwenn" aus einem anderen Tabellenblatt aktualisiert werden, ändert sich der Zeitstempel nicht.

Hat jemand eine Lösung für mein Problem ?
This comment was minimized by the moderator on the site
Hello Michael Rasche,
The formula issue cannot be handled yet. Sorry for the inconvenience.
This comment was minimized by the moderator on the site
Hallo,
ich möchte auch gerne in einer Tabelle einen Zeitstempel setzen, und bin bei der Suche auf diese Seite gestossen.
Ich habe alles wie oben beschrieben eingegeben, jetzt ergibt sich noch folgendes Problem:
Der Zeitstempel soll sich ändern, wenn sich der Wert in Spalte G ändert, der Wert in Spalte bildet sich aus der Summe mehrerer Zellen (z.B. K 150 - AA 150) in der Reihe.
Wenn ich einen neuen Wert direkt in die Zellen eingebe funktioniert das VBA.
Bei meiner Tabelle ändern sich die Werte in z.B. K 150 - AA 150 aber durch die "Zählenwenn" Funktion aus einem anderen Tabellenblatt, wenn sich dann die Summe erhöht, ändert sich der Zeitstempel nicht.
Hat jemand eine Lösung für mich ?
This comment was minimized by the moderator on the site
how do I add this on two columns? to have two timestamps for two column on input???
This comment was minimized by the moderator on the site
Hi, finally I found this post. Thankyou I Needed this. But can anyone help me, I want to change the code so that instead of tracking the changes on the current worksheet, I want the code to track the changes on selected Columns from other worksheet, then insert the timestamp to the current worksheet.
This comment was minimized by the moderator on the site
Hi, finally i found this post. Thankyou I Needed this. But can anyone help me, I want to change the code so that instead of tracking the changes on the current worksheet, I want the code to track the changes on selected Columns from other worksheet, then insert the timestamp to the current worksheet.
This comment was minimized by the moderator on the site
Hi, This is great info, but I'm having problem. I would like to use for change in column A time stamp column B and change in column D with time stamp column E and change in column G with time stamp column H. I can not figure out. Help please.
This comment was minimized by the moderator on the site
Hi, Is there a chance you can help me? I have tried the VBA code for the timestamp:
Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20180830
Dim xCellColumn As Integer
Dim xTimeColumn As Integer
Dim xRow, xCol As Integer
Dim xDPRg, xRg As Range
xCellColumn = 3
xTimeColumn = 5
xRow = Target.Row
xCol = Target.Column
If Target.Text <> "" Then
If xCol = xCellColumn Then
Cells(xRow, xTimeColumn) = Now()
Else
On Error Resume Next
Set xDPRg = Target.Dependents
For Each xRg In xDPRg
If xRg.Column = xCellColumn Then
Cells(xRg.Row, xTimeColumn) = Now()
End If
Next
End If
End If
End Sub

My problem is that I have to add dates in column 22 and I need the timestamp in column 21. The above code does not work in my sheet. I have tried it with timestamp functions and formulas, but it always changes it to the date when I opened the workbook.
I also tried to work with conditional formatting that the another cell changes the colour when the cell with the timestamp is not todays date, but this does not work either. Can you let me know what I do wrong?
This comment was minimized by the moderator on the site
Hi Lina,
Do you mean manually enter dates in column 22 and then populate timestamp automatically in adjacent cells in column 21?
You just need to change the column numbers in the code to get it down. If you only want to display time, replace the NOW() with Time() in the code. See the below code.

<div data-tag="code">Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20201106
Dim xCellColumn As Integer
Dim xTimeColumn As Integer
Dim xRow, xCol As Integer
Dim xDPRg, xRg As Range
xCellColumn = 22
xTimeColumn = 21
xRow = Target.Row
xCol = Target.Column
If Target.Text <> "" Then
If xCol = xCellColumn Then
Cells(xRow, xTimeColumn) = Time()
Else
On Error Resume Next
Set xDPRg = Target.Dependents
For Each xRg In xDPRg
If xRg.Column = xCellColumn Then
Cells(xRg.Row, xTimeColumn) = Time()
End If
Next
End If
End If
End Sub
This comment was minimized by the moderator on the site
Thank you for your response. Yes, that's what I wanted to do. I tried the above VBA code before but for some reason it did not work, but it works fine now. Thank you for your help
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