Saltar al contenido principal

¿Cómo proteger las celdas según la fecha en Excel?

Normalmente, podemos proteger la hoja de trabajo para evitar que otros editen o modifiquen los valores de las celdas, pero, a veces, es necesario proteger las celdas según la fecha. Por ejemplo, quiero proteger otras celdas pero solo permitir que los valores de celda de la fecha de hoy se modifiquen como se muestra en la siguiente captura de pantalla, este artículo hablará sobre cómo proteger las celdas según la fecha.

doc proteger por fecha 1

Proteja todas las filas excepto la fila de la fecha de hoy con código VBA

Proteja todas las filas que la fecha haya pasado con el código VBA


flecha azul burbuja derecha Proteja todas las filas excepto la fila de la fecha de hoy con código VBA

Solo permita que se modifique la fila que es igual a la fecha de hoy, el siguiente código puede ayudarlo, haga lo siguiente:

1. Haga clic con el botón derecho en la pestaña de la hoja en la que desea proteger las celdas según la fecha y luego elija Ver código en el menú contextual, en el emergente Microsoft Visual Basic para aplicaciones ventana, copie y pegue el siguiente código en el módulo en blanco:

Código de VBA: proteja todas las filas excepto la fila de la fecha de hoy:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Updateby Extendoffice 20161025
    If Range("E" & Selection.Row).Value <> Date Then
        ActiveSheet.Protect Password:="111111"
        MsgBox "Only today's date row can be edited!", vbInformation, "Kutools for Excel"
    ElseIf Range("E" & Selection.Row).Value = Date Then
        ActiveSheet.Unprotect Password:="111111"
        ActiveSheet.EnableSelection = xlNoRestrictions
    End If
End Sub

doc proteger por fecha 2

Note: En el código anterior, la letra E es el encabezado de la columna donde se encuentra la fecha, "111111”Es la contraseña para proteger esta hoja. Puede cambiarlos según sus necesidades.

2. Luego guarde y cierre esta ventana de código.

(1.) Si hace clic en otras celdas más allá de la fila de la fecha de hoy, aparecerá un cuadro emergente para recordarle que la celda no se puede editar, vea la captura de pantalla:

doc proteger por fecha 3

(2.) Si hace clic y edita la fila es igual a la fecha de hoy, se modificará correctamente, vea la captura de pantalla:

doc proteger por fecha 4


flecha azul burbuja derecha Proteja todas las filas que la fecha haya pasado con el código VBA

Si necesita proteger todas las filas a partir de la fecha, solo permita que se modifiquen las filas de fechas actuales y futuras, aplique el siguiente código VBA:

1. Haga clic con el botón derecho en la pestaña de la hoja en la que desea proteger las celdas según la fecha y luego elija Ver código en el menú contextual, en el emergente Microsoft Visual Basic para aplicaciones ventana, copie y pegue el siguiente código en el módulo en blanco:

Código de VBA: proteger todas las filas, la fecha ha pasado:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
'Updateby Extendoffice 20161025
  Dim xRow As Long
  xRow = 2
  ThisWorkbook.ActiveSheet.Unprotect Password:="111111"
  ThisWorkbook.ActiveSheet.Cells.Locked = False
  Do Until IsEmpty(Cells(xRow, 5))
    If Cells(xRow, 5) < Date Then
      Rows(xRow).Locked = True
    End If
    xRow = xRow + 1
  Loop
  ThisWorkbook.ActiveSheet.Protect Password:="111111"
End Sub

doc proteger por fecha 5

Note: En el código anterior, el número 5 es el número de columna donde se ubica la fecha, "111111”Es la contraseña para proteger esta hoja. Puede cambiarlos según sus necesidades.

3. Luego guarde y cierre esta ventana de código.

(1.) Si hace clic en la fecha de la celda, aparecerá un cuadro emergente para recordarle que la celda no se puede editar, vea la captura de pantalla:

doc proteger por fecha 6

(2.) Si hace clic en la celda de filas para intentar cambiar los valores en la fecha de hoy o en la fecha futura, se modificará correctamente, vea la captura de pantalla:

doc proteger por fecha 7

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 (30)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hello, I would like to protect future days and allow editing current and past days. How do I do that?
This comment was minimized by the moderator on the site
Hello, Miguel,To protect the future days, please apply the below code:<div data-tag="code">Private Sub Worksheet_Change(ByVal Target As Excel.Range)
'Updateby Extendoffice
Dim xRow As Long
xRow = 2
ThisWorkbook.ActiveSheet.Unprotect Password:="111111"
ThisWorkbook.ActiveSheet.Cells.Locked = False
Do Until IsEmpty(Cells(xRow, 5))
If Cells(xRow, 5) > Date Then
Rows(xRow).Locked = True
End If
xRow = xRow + 1
Loop
ThisWorkbook.ActiveSheet.Protect Password:="111111"
End SubPlease try, hope it can help you!
This comment was minimized by the moderator on the site
hello i did it but when i press cell message shows that it can not be edited but when i press keyborad i still can write in the cell
This comment was minimized by the moderator on the site
Hello, I tried to do the same but to Protect all columns except today’s date column with VBA code by replacing "Selection.Row" with "Selection.Columns" and "E" with "5" (row number where dates are), but I keep receiving error 1004!

Any help please?

Thank you
This comment was minimized by the moderator on the site
Hello,
To apply this code to columns that you need, please use the following VBA code:(Note: In the code, 5 is the row number contains the date, please change it to your need.)

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim xRg As Range
Set xRg = Target.Worksheet.Cells(5, Target.Column)
If xRg <> Date Then
ActiveSheet.Protect Password:="111111"
MsgBox "Only today's date row can be edited!", vbInformation, "Kutools for Excel"
ElseIf xRg.Value = Date Then
ActiveSheet.Unprotect Password:="111111"
ActiveSheet.EnableSelection = xlNoRestrictions
End If
End Sub

Please try, hope it can help you!
This comment was minimized by the moderator on the site
Hi Im facing one problem, once i close the file and reopens it again on the same date, code doesnot work. pls help im stuck
This comment was minimized by the moderator on the site
Hi, rohit,
To keep the code, you should save your workbook as Excel Macro-Enabled Workbook format, please try, thank you!
This comment was minimized by the moderator on the site
Thanks for your help, Thanku so much buddy, It is a great help. and solved my tension.
Be safe
RegardsRohit Khanna
This comment was minimized by the moderator on the site
Thank you! Sorry, I did not get your reply until now, it might be a problem in my email.

It worked! Can't say thank you enough! I really appreciate that!
This comment was minimized by the moderator on the site
Hi,
Glad it can help you!
This comment was minimized by the moderator on the site
Hi,

I am trying to expand this to protect columns that do not include this current month or/and this current week. I tried to replace "Date" with "month" or "week", but did not work.

I have attached a sample for weeks sheet where user cannot edit or type in columns other than this week.

Any advice on that? or shall I use actual dates to reflect a day in the month?
This comment was minimized by the moderator on the site
Hello, I tried to do the same but to Protect all columns except today’s date column with VBA code by replacing "Selection.Row" with "Selection.Columns" and "E" with "5" (row number where dates are), but I keep receiving error 1004!

Any help please?

Thank you
This comment was minimized by the moderator on the site
Hi,

while running this code I am getting an error as shown in the figure
Also i am attaching a snapshot my excel where i want to make changes..

Can u guide in my code where should i make changes according to my excel file so that cells that contain only todays & future date can be editied ???
This comment was minimized by the moderator on the site
Hello, Karan,
Because there are merged cells in your table, the above code can not be applied correctly in merged cells table.
If you have any other good ideas, please comment here. Thank you!
This comment was minimized by the moderator on the site
As someone who is relatively new to VBA, would you mind explaining why xRow = 2 in Line 4?



Thanks
This comment was minimized by the moderator on the site
because in row no. 1 you have header
This comment was minimized by the moderator on the site
This works great. but how can I switch it to unlock a column based on dates in row 3?
This comment was minimized by the moderator on the site
Hello.....


I am using the code for Protect all rows except today’s date row........



Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Updateby Extendoffice 20161025
If Range("A" & Selection.Row).Value <> Date Then
ActiveSheet.Protect Password:="111111"
MsgBox "Only today's date row can be edited!", vbInformation, "Kutools for Excel"
ElseIf Range("E" & Selection.Row).Value = Date Then
ActiveSheet.Unprotect Password:="111111"
ActiveSheet.EnableSelection = xlNoRestrictions
End If
End Sub


After i save i and click on cell i get message only today's date row can be edited....but if i double click the cell the i can edit...pls help
This comment was minimized by the moderator on the site
hi is it possible to lock certain cells depending on the date that is directly above them in a column?
This comment was minimized by the moderator on the site
Hi, Lusis,
Can you give your problem more specifically? Or you can attach a screenshot as your problem.
Thank you!
This comment was minimized by the moderator on the site
Hi skyyang

Yes here is a screenshot. Hope this helps.
This comment was minimized by the moderator on the site
Here it is.
This comment was minimized by the moderator on the site
Hello, Lucis,
Do you mean to lock the columns which date is past, and only the columns of today and future days can be modified?
This comment was minimized by the moderator on the site
Correct! How would I go about that?
This comment was minimized by the moderator on the site
Hi, Luis,
How about the date cell in A1? Is it entered manually or entered with a formula =now()? If it is a formula cell, the locked columns will be changed with the date changes.
Looking forward to your reply!
This comment was minimized by the moderator on the site
Hi Skyyangg

yes the cell A1 has the =now() formula.

thanks!
This comment was minimized by the moderator on the site
Hi is it possible to lock columns by the date directly above the columns?
This comment was minimized by the moderator on the site
Private Sub worksheet_Change(ByVal Target As Range)

'Subscribe to http://youtube.com/excel10tutorial

'Support the channel by donating on http://patreon.com/excel10tutorial

Dim col As Range

'Set the correct sheet name here:

With ThisWorkbook.Sheets("AGOSTO-22")

.Unprotect "ABCDE"

For Each col In .UsedRange.Columns

col.EntireColumn.Locked = col.Range("A1").Value <> Date

Next col

.Protect "ABCDE"

.EnableSelection = xlNoRestrictions

End With

End Sub
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