切换"突出显示边界"围绕用户选择的单元格

时间:2016-03-28 18:51:46

标签: excel vba excel-vba

我有一些代码可以为用户生成一个简单的Excel模板。该代码锁定并保护所有不在" A2:A"并使它们无法选择。但是,在此代码运行后,用户不再获得围绕所选单元格的突出显示。有没有办法确保在代码中启用它?

With ws1
    .Protect UserInterfaceOnly:=True
    .EnableSelection = xlUnlockedCells
    With .Cells
        .Locked = True
        .Borders.Color = vbWhite
    End With

    With .Columns("A")
        .Locked = False
        .Borders.Color = vbBlack
        .ColumnWidth = 20
    End With

    With .Range("A1")
        .Value = "MPID"
        .Interior.Color = 14277081
        .HorizontalAlignment = xlCenter
        .Locked = True
    End With
End With

1 个答案:

答案 0 :(得分:1)

使用限制Excel工作表时,您必须以反向逻辑方式处理它。一旦您单击或激活限制工作表的宏,默认情况下一切都将受到限制。因此,您首先必须选择并更改单元格上的“已锁定”值或首先将范围设置为false。然后,您应该按照您希望的方式设置其他所有内容,最后一步是主动限制工作表。这应该给你你想要的东西:

Sub Test()

    Dim ws1 As Worksheet
    Set ws1 = Sheets("Sheet1")

    'unprotect the column that you don't want to restrict
    Columns("A:A").Select
    Selection.Locked = False
    Selection.FormulaHidden = False

    With ws1.Range("A1")
        .Value = "MPID"
        .Interior.Color = 14277081
        .HorizontalAlignment = xlCenter
    End With

    With ws1.Columns("A")
        .Borders.Color = vbBlack
        .ColumnWidth = 20
    End With

    ws1.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
    ws1.EnableSelection = xlUnlockedCells

    Set ws1 = Nothing

End Sub