Excel 2003 VBA - 如果日期范围内,则锁定列

时间:2014-06-02 17:13:03

标签: excel vba excel-vba

我正在尝试锁定标题中具有特定日期范围的所有列。此代码运行但只锁定整个文档。

日期范围为B2到DD2,格式为dd / mm / yyyy

我想在上周五之前锁定所有列。因此,每次打开电子表格时,它都会检查当前日期,查找上周五,然后锁定范围内的所有列,以便无法进行编辑。

非常感谢一些帮助,我第一次去VBA吧。

Private Sub Workbook_Open()
Worksheets("Data").Activate
ProtectTheSheet
End Sub

Function dteLastFriday(dte As Date) As Date
Dim x As Integer
x = Weekday(dte)
If x = 7 Then
    dteLastFriday = dte - 1
Else
    dteLastFriday = dte - 1 - x
End If
End Function

Function ProtectTheSheet()
Dim chCell As Range
Dim chRng As Range

ActiveSheet.Unprotect
Set chRng = ActiveSheet.Range("B2:DD2")

For Each chCell In chRng.Cells
    If chCell < dteLastFriday(Date) Then
        chCell.Locked = (chCell.Value <> "")
    End If
Next chCell

ActiveSheet.Protect

End Function

2 个答案:

答案 0 :(得分:1)

您可能需要在比较之前将单元格值转换为日期:

If CDate(chCell) < dteLastFriday(Date) Then

如果您想要锁定整个列:

chCell.EntireColumn.Locked = True

此测试chCell.Value <> ""可能始终为True(或始终为False),因为您已经测试了它的值。

但是默认情况下单元格已锁定,因此您需要先解锁它们:

ActiveSheet.UsedRange.Locked = False

答案 1 :(得分:0)

试试这个:

Sub ProtectTheSheet()
    Dim chCell As Range
    Dim chRng As Range
    Dim lFriday As Date

    With ActiveSheet
        .Unprotect
        'unlock all cells
        .Cells.Locked = False
        Set chRng = .Range("B2:DD2")
        'calculate it once rather than each iteration in loop
        lFriday = dteLastFriday(Date)

        For Each chCell In chRng.Cells
            If chCell.Value < lFriday And chCell.Value <> "" Then
                chCell.EntireColumn.Locked = True 
            End If
        Next chCell

        .Protect
    End With
End Sub

和你的职能:

Function dteLastFriday(dte As Date) As Date
    Dim x As Integer
    x = Weekday(dte)
    If x = 7 Then
        dteLastFriday = dte - 1
    Else
        dteLastFriday = dte - 1 - x
    End If
End Function