2016-05-14 63 views
0

我正在使用以下代碼在G11到G55中隱藏公式。但它隱藏了所有公式並保護了工作表4。我怎樣才能隱藏和保護G15:G55中的細胞?謝謝。在Excel中的所選範圍中隱藏公式

Sub Loc() 
    Dim c As Range 
    Worksheets("sheet4").Range("G15:G55").Select 

    For Each c In Selection 
     If c.HasFormula = True Then 
      c.Locked = True 
      c.FormulaHidden = True 
     End If 
    Next c 
    'Worksheets("sheet4").Range("G11:G55").Locked = True 
    Worksheets("sheet4"").Protect Password:="111" 
End Sub 

可以下面的代碼進行修改

Sub Locs() 
    Dim c As Range, rng1, rng2 As Range 
    Worksheets("Sheet4").Unprotect Password:="111" 

    Cells.Locked = False 
    Cells.FormulaHidden = False 

    Set rng1 = Range("G15:G55") 
    Set rng2 = Range("I15:I55") 

    For Each c In rng1 
     If c.HasFormula = True Then 
      c.Locked = True 
      c.FormulaHidden = True 
     End If 
    Next c 

    For Each c In rng2 
     If c.HasFormula = True Then 
      c.Locked = True 
      c.FormulaHidden = True 
     End If 
    Next c 

    Worksheets("Sheet4").Protect Password:="111" 
End Sub 
+0

您只需要一個**設置**並且只有一個循環........................'Set rng = Union(Range(「G15 :G55「),範圍(」I11:I55「))' –

+0

@ Gary的謝謝............................... – Kuma

回答

1

考慮:

Sub Loc() 
    Dim c As Range, rng As Range 

    Worksheets("sheet4").Unprotect Password:="111" 
     Cells.Locked = False 
     Cells.FormulaHidden = False 
     Set rng = Range("G15:G55") 

     For Each c In rng 
      If c.HasFormula = True Then 
       c.Locked = True 
       c.FormulaHidden = True 
      End If 
     Next c 
    Worksheets("sheet4").Protect Password:="111" 
End Sub 

此只鎖定感興趣的細胞並釋放其他人。如果您願意,您可以將G15更改爲G11

+0

@ Gary's這很好,我想要它去另一個範圍,有沒有簡單的方法來修改代碼, – Kuma

+0

@Kuma這是所有在**設置**命令.....你可以改變這個包括一個不同的範圍或一組不同的範圍.................... –