根据datelocking整个行

我提到了有月份的单元格A1。 我想比较date在A2:最后一个单元格和无论哪里date> A1,我想这行被解锁,否则locking。 下面的代码不起作用“

Sub Lockrow() Dim DestSh As Worksheet Dim lastrow As Long Dim i As Integer Set DestSh = Sheets("Consultant & Volunteer") With DestSh 'finds the last row with data on A column lastrow = .Range("A" & .Rows.Count).End(xlUp).Row 'parse all rows For i = 6 To lastrow 'if your conditions are met If Month(.Cells(i, 26)) > Month(.Cells(1, 1)) Then .Range("A" & i).EntireRow.Cells.Locked = True 'lock the row End If Next i End With End Sub 

这可以简单地用下面的方法来完成,但是你必须小心,年份不会改变…另外, lastrow应该在Z列上。

另外,如果工作表不受保护,则不起作用。

 Option Explicit Sub Lockrow() Dim DestSh As Worksheet Dim lastrow As Long Dim i As Long ' Integer Set DestSh = Sheets("Consultant & Volunteer") With DestSh 'finds the last row with data on A column lastrow = .Range("Z" & .Rows.Count).End(xlUp).Row ' <-- EDIT 'parse all rows For i = 6 To lastrow 'if your conditions are met .Rows(i).Locked = Not (Month(.Cells(i, "Z")) > Month(.Range("A1"))) ' If Month(.Cells(i, 26)) > Month(.Cells(1, 1)) Then ' .Range("A" & i).EntireRow.Cells.Locked = True 'lock the row ' End If Next i .Protect UserInterfaceOnly:=True End With Set DestSh = Nothing End Sub 

替代循环。

 Dim r As Range, DestSh As Worksheet, lastrow As Long Set DestSh = Sheets("Consultant & Volunteer") With DestSh lastrow = .Range("A" & .Rows.Count).End(xlUp).Row Set r = .Range("A1:A" & lastrow) r.EntireRow.Locked = False r.AutoFilter 1, ">" & .Range("A1").Value2 r.SpecialCells(xlCellTypeVisible).EntireRow.Locked = True .AutoFilterMode = False .Protect UserInterfaceOnly:=True End With