隐藏Excel中所选范围内的公式

时间:2016-05-14 14:45:36

标签: excel excel-vba vba

我使用以下代码隐藏G11到G55中的公式。但它隐藏了所有公式并保护了sheet4。我怎样才能在G15:G55中隐藏和保护细胞?谢谢。

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

1 个答案:

答案 0 :(得分: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