如何使用循环来锁定所有现有工作表中的单元格范围

时间:2013-07-22 20:20:41

标签: excel

我有一个包含50多个工作表的存在工作簿。我需要为每个存在的工作表锁定单元格范围(b7:b51)。我尝试使用循环来做它,我有一个循环的代码,它通过所有工作表,我需要输入正确的代码来锁定单元格。

   Sub WorksheetLoop()

     Dim WS_Count As Integer
     Dim I As Integer

     ' Set WS_Count equal to the number of worksheets in the active
     ' workbook.
     WS_Count = ActiveWorkbook.Worksheets.Count

     ' Begin the loop.
     For I = 2 To WS_Count

   ActiveSheet.range("B1:B51").locked=true. --this is not correct.


    MsgBox ActiveWorkbook.Worksheets(I).Name


     Next I

  End Sub

感谢

3 个答案:

答案 0 :(得分:1)

试试这个......

Sub WorksheetLoop()

 Dim WS_Count As Integer
 Dim I As Integer

 ' Set WS_Count equal to the number of worksheets in the active
 ' workbook.
 WS_Count = ActiveWorkbook.Worksheets.Count

 ' Begin the loop.
 For I = 1 To WS_Count

If Worksheets(I).Range("C1:C51").Locked <> True Then
  Worksheets(I).Range("C1:C51").Locked = True
  Worksheets(I).Protect Contents:=True
Else
End If

MsgBox ActiveWorkbook.Worksheets(I).Name


 Next I

End Sub

答案 1 :(得分:1)

Public Sub ProtectRange()
Dim i As Integer, wsCount As Integer

wsCount = ActiveWorkbook.Worksheets.Count

For i = 1 To wsCount
    ActiveWorkbook.Worksheets(i).Range("B1:B51").Locked = True
    ActiveWorkbook.Worksheets(i).Protect Contents:=True
Next i

End Sub

答案 2 :(得分:1)

这应该这样做。

Sub Macro1()

Dim WS_Count As Integer
     Dim I As Integer

     ' Set WS_Count equal to the number of worksheets in the active
     ' workbook.
     WS_Count = ActiveWorkbook.Worksheets.Count

     ' Begin the loop.
     For I = 2 To WS_Count

        Dim sheet As Worksheet
        Set sheet = Sheets(I)

        sheet.Unprotect

        sheet.UsedRange.Locked = False
        sheet.Range("B7:B51").Locked = True
        sheet.Protect Contents:=True

        MsgBox ActiveWorkbook.Worksheets(I).Name

     Next I

End Sub