2013-07-22 37 views
0

我有一個存在的工作簿有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 

感謝

+1

您是否只想鎖定「B7:B51」並鎖定所有其他單元格?默認情況下,當您保護表單時,單元格爲「鎖定」。實際上,您必須「解鎖」您要使用的單元格,並在「鎖定」時保留其他單元格。 – chancea

+0

是的,我只需要B7:B51鎖定。非常感謝你 –

回答

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 
+0

我嘗試了代碼,並且顯示這行錯誤 工作表(I).Range(「B1:B281」)。Locked = True –

+0

你在這裏得到了什麼錯誤? –

+0

好的。看起來這些單元格已經鎖定。 嘗試此 如果工作表(I).Range( 「B1:B51」)。鎖定<>真,那麼 工作表(I).Range。( 「B1:B51」)鎖定=真 工作表(I )。保護內容:=真 其他 結束如果 –

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 
+0

@AndyG謝謝,編輯答案。 – rwisch45

+0

謝謝。但我在這一行中得到錯誤:ActiveWorkbook.Worksheets(i).Range(「B1:B281」)。Locked = True –

+0

請注意告訴我們錯誤是什麼? –

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 
+0

非常感謝。有用 –

相關問題