如何将列锁定到包含数据

时间:2016-09-23 11:14:34

标签: excel excel-vba vba

我在单元格A1中提到日期,前 - “五月”。

我现在正试图用列Z锁定2-last行,其中提到每个员工的加入日期并将其与A1进行比较。

如果该单元格Z的月份是> A1然后我试图锁定该行。不知道该怎么办。

下面的代码没有帮助:

Sub Lockrow()
Dim DestSh As Worksheet
Dim lastrow As Long
Dim i As Integer

Set DestSh = Sheets("Consultant & Teacher")

With DestSh
    'finds the last row with data on A column
    lastrow = Range("A65536").End(xlUp).Row

    'parse all rows
    For i = 6 To lastrow
       'if your conditions are met
       If Month(.Cells(i, 26)) > Month(.Cells(1, 2)) Then
          .Range("A" & i).EntireRow.Cells.Locked = True 'lock the row
       End If
    Next i
End With

End Sub

1 个答案:

答案 0 :(得分:3)

这是你在尝试的吗?

Sub Sample()
    Dim DestSh As Worksheet
    Dim lastrow As Long

    '~~> Change this as applicable
    Set DestSh = Sheets("Sheet1")

    With DestSh
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            lastrow = .Columns("A:C").Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row
        Else
            MsgBox "Insufficient rows"
            Exit Sub
        End If

        .Unprotect "MyPassword"
        .Cells.Locked = False

        .Range("A6:C" & lastrow).Locked = True

        .Protect "MyPassword"
    End With
End Sub