简体   繁体   English

在Excel VBA中锁定单元格

[英]Lock Cell in Excel VBA

The code below doesn't work when I have my workbook protected (it does work when nothing is protected). 当我的工作簿受到保护时,下面的代码不起作用(当没有任何保护时,它起作用。) What I am trying to do is having a workbook and sheets protected except for few cells and after a specific data I want all cells to be protected, please help. 我想做的是保护工作簿和工作表,除了几个单元格外,在特定数据之后,我希望所有单元格都受到保护,请帮忙。

Sub Workbook_Open()

    If Date >= DateSerial(2016, 1, 19) Then
       Worksheets("Jan").Protect Password:="123"

    ElseIf Date >= DateSerial(2016, 2, 28) Then
       Worksheets("FEB").Protect Password:="123"

    ElseIf Date >= DateSerial(2016, 3, 31) Then
       Worksheets("MAR").Protect Password:="123"

    ElseIf Date >= DateSerial(2016, 4, 30) Then
       Worksheets("Apr").Protect Password:="123"

    End If
End Sub

Appears to work when I tested it - could it be that it isn't protecting each sheet, just the first sheet that meets the test. 在我测试它时似乎可以正常工作-可能是它没有保护每张纸,只是保护了符合测试条件的第一张纸。 So, in February If Date >= DateSerial(2016, 1, 19) will be TRUE, so it'll protect January again and exit the procedure - it'll never even look at the FEB sheet. 因此,在2 If Date >= DateSerial(2016, 1, 19)将为TRUE,那么它将再次保护1月并退出该过程-它甚至不会查看FEB表。

I'm assuming the January date should be 31 rather than 19. 我假设1月的日期应该是31,而不是19。

Try: 尝试:

Private Sub Workbook_Open()

    Dim wrkSht As Worksheet
    Dim dSheet As Date

    'Look at each sheet.
    For Each wrkSht In ThisWorkbook.Worksheets
        'Create first of month date from sheet name.
        dSheet = CDate("1-" & wrkSht.Name & "-" & Year(dSheet))
        'Calculate last day of month (day zero of the following month).
        dSheet = DateSerial(Year(dSheet), Month(dSheet) + 1, 0)

        'Check the date against todays date and protect.
        If Date >= dSheet Then
            wrkSht.Protect Password:="123"
        End If

    Next wrkSht

End Sub

To test change dSheet = CDate("1-" & wrkSht.Name & "-" & Year(dSheet)) to dSheet = CDate("1-" & wrkSht.Name & "-" & 2015) 要测试将dSheet = CDate("1-" & wrkSht.Name & "-" & Year(dSheet))更改为dSheet = CDate("1-" & wrkSht.Name & "-" & 2015)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM