Excel 2003 VBA – lockingdate范围内的列
我试图locking在标题中有一定的date范围的所有列。 此代码运行,但只是locking整个文件。
date的格式为dd / mm / yyy,格式为B2到DD2
我想在上周五之前locking所有列。 所以每次打开电子表格时,都会检查当前date,find上个星期五,然后locking范围内的所有列,以便无法进行编辑。
真的很感谢一些帮助,我的第一个正确的去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
试试这个:
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:
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
在比较之前,您可能需要将单元格值转换为date:
If CDate(chCell) < dteLastFriday(Date) Then
如果您然后想要locking整个列:
chCell.EntireColumn.Locked = True
这个testingchCell.Value <> ""
可能总是为真(或者总是为False),因为你已经testing了它的值。
但是单元默认是locking的,所以你需要先解锁它们:
ActiveSheet.UsedRange.Locked = False