如何在excel vba中的行之间锁定

时间:2017-02-07 09:44:14

标签: excel vba excel-vba

我想根据两列的值锁定excel表格的行之间, 我跟随我的代码,但是这样可以保护整张纸 代码是:

当循环转到else它抛出“无法设置范围类的锁定属性”的部分时,还有另一个问题,代码是:

Do While xlsht.Cells(i, 1) <> vbNullString
            If (CStr(xlsht.Cells(i, 54).Value) <> "" And (CStr(Format(xlsht.Cells(i, 55).Value, "dd-MMM-yyyy")) = CStr(Format(Now, "dd-MMM-yyyy")))) Then
                    .Cells.Locked = False
                    .Range("A" & i & " : " & "BH" & i).Cells.Locked = True
                    .Range("A" & i & " : " & "BH" & i).Interior.Color = RGB(255, 255, 0)
                    .Protect Password:=admin
            Else
                    .Cells.Locked = False
                    .Range("A" & i & " : " & "AC" & i).Cells.Locked = True
                    .Range("AE" & i & " : " & "AT" & i).Cells.Locked = True
                    .Range("BB" & i & " : " & "BH" & i).Cells.Locked = True
                    .Protect Password:=admin
            End If
                i = i + 1
            Loop

    End With

2 个答案:

答案 0 :(得分:4)

你可能会这样:

    Dim i As Long

    i = 1
    With Worksheets("mySheetName") '<--| change "mySheetName" to your actual sheet name
        Do While .Cells(i, 1) <> ""
            If (.Cells(i, 54).Value = "abc" And .Cells(i, 55).Value = "def") Then Intersect(.Range("A:BH"), .Rows(i)).Locked = True
        i = i + 1
        Loop
        .Protect Password:="admin"
    End With

答案 1 :(得分:2)

默认情况下,整张工作表已锁定(范围或单元格的属性)。

您只能保护整张表。

所以你必须首先解开剩下的表格!

i = 1
With xlsht
    .Unprotect Password:=admin
    .Cells.Locked = False
    Do While xlsht(i, 1) <> vbNullString
       If .Cells(i, 54).Values = "abc" And .Cells(i, 55).Values = "def" Then
           'here is checking the column depends the row is get lock or not
           .Range("A" & i & ":BH" & i).Cells.Locked = True
           i = i + 1
       End If
    Loop
    .Protect Password:=admin
End With 'xlsht

第二个问题

i = 1
With xlsht
    .Unprotect Password:=admin
    .Cells.Locked = False
    Do While .Cells(i, 1).Value <> vbNullString
        If CStr(.Cells(i, 54).Value) <> vbNullString And CDate(.Cells(i, 55).Value) = Date Then
            With .Range("A" & i & ":BH" & i)
                .Cells.Locked = True
                .Interior.Color = RGB(255, 255, 0)
            End With '.Range("A" & i & ":BH" & i)
        Else
            .Range("A" & i & ":AC" & i).Cells.Locked = True
            .Range("AE" & i & ":AT" & i).Cells.Locked = True
            .Range("BB" & i & ":BH" & i).Cells.Locked = True
        End If
        i = i + 1
    Loop
    .Protect Password:=admin
End With 'xlsht