使某些细胞不可编辑

时间:2018-02-13 13:55:26

标签: vba excel-vba excel

我有这个代码,如果列E显示为灰色,则会显示D列的一部分,并使E列着色,反之亦然。

而不是让它变灰,我想让细胞不可编辑。

这可能吗?

Dim sourceCell1 As Range, targetRng1 As Range, sourceCell2 As Range, targetRng2 
 As Range
 With Worksheets("SHELLY")
 If .Range("D3:D19").Interior.ColorIndex = 15 Then
    Set sourceCell1 = .Range("C41")
    Set targetRng1 = .Range("F3:F19")
    Set sourceCell2 = .Range("C42")
    Set targetRng2 = .Range("D3:D19")
 Else
    Set sourceCell1 = .Range("C41")
    Set targetRng1 = .Range("D3:F19")
    Set sourceCell2 = .Range("C43")
    Set targetRng2 = .Range("F3:F19")
 End If
 End With

sourceCell1.Copy
targetRng1.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False

sourceCell2.Copy
targetRng2.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False

1 个答案:

答案 0 :(得分:0)

扩展@DisplayName的评论,低于How to Lock the data in a cell in excel using vba的应用程序。

Sub lockRange()
    Dim sourceCell1 As Range, targetRng1 As Range, sourceCell2 As Range, targetRng2 As Range

    With Worksheets("SHELLY")

        'unprotect sheet to make alterations
        .Unprotect Password:="p"
        'making range editable before protecting sheet
        .Range("A1:AA100").Locked = False

        If .Range("D3:D19").Interior.ColorIndex = 15 Then
            Set sourceCell1 = .Range("C41")
            Set targetRng1 = .Range("F3:F19")
            Set sourceCell2 = .Range("C42")
            Set targetRng2 = .Range("D3:D19")

            'defining which range to lock
            Set lockRng = .Range("D3:D19")
        Else
            Set sourceCell1 = .Range("C41")
            Set targetRng1 = .Range("D3:F19")
            Set sourceCell2 = .Range("C43")
            Set targetRng2 = .Range("F3:F19")

            'defining which range to lock
            Set lockRng = .Range("F3:F19")
        End If
    End With

    sourceCell1.Copy
    targetRng1.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False

    sourceCell2.Copy
    targetRng2.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False

    With Worksheets("SHELLY")
        'locking range so it is un-editable when protected
        lockRng.Locked = True
        'range E always gray/locked?
        .Range("E3:E19").Locked = True
        'protecting sheet with password
        .Protect UserInterfaceOnly:=True, Password:="p"
    End With
End Sub