vba 更改活动单元格填充颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42210554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:07:01  来源:igfitidea点击:

change active cell fill color

excel-vbavbaexcel

提问by Mansour

I have a workbook with some protected sheets.
Users enter data into specific cells of each sheet.
I want the active cell background color to change - for example to red - when it is highlighted and back to the original color when deselected.
I would like to find a macro to assign it to the workbook instead of each worksheet.

我有一个带有一些受保护工作表的工作簿。
用户将数据输入到每个工作表的特定单元格中。
我希望活动单元格背景颜色在突出显示时更改 - 例如更改为红色,并在取消选择时返回原始颜色。
我想找到一个宏来将它分配给工作簿而不是每个工作表。

I think this code is useful but since I'm a beginner I don't know which parameter should be changed to fit my demand.

我认为这段代码很有用,但由于我是初学者,我不知道应该更改哪个参数以满足我的需求。

Sub ColorCells()
    Dim Data As Range
    Dim cell As Range
    Set currentsheet = ActiveWorkbook.Sheets("Ekandari")
    Set Data = currentsheet.Range("C5:D5,F5:M5,L9")
    For Each cell In Data
        cell.Interior.ColorIndex = 3
    Next
End Sub

回答by Hasib_Ibradzic

Mansour, this should help. Unfortunately it does not work for the entire workbook. You will need to add this code to each sheet in the workbook. If you do not have a password then you will need to delete the "password" from the second line

曼苏尔,这应该有帮助。不幸的是,它不适用于整个工作簿。您需要将此代码添加到工作簿中的每个工作表。如果您没有密码,则需要从第二行中删除“密码”

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    ActiveSheet.Unprotect "password"

    On Error Resume Next
    Range("PrevCell").Interior.ColorIndex = 0

    ActiveCell.Interior.ColorIndex = 3
    With ActiveWorkbook.Names("PrevCell")
        .RefersTo = ActiveCell
    End With

    ActiveSheet.Protect Password:="password", DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
End Sub

The only change you need to make is if you don't want the active color to be red, then change the 3 to whichever color index you want to use.

您需要进行的唯一更改是,如果您不希望活动颜色为红色,则将 3 更改为您要使用的任何颜色索引。

回答by Mansour

This is the simplest code i've found that sets background and active cell colors. note: put it in (Thisworkbook)

这是我发现设置背景和活动单元格颜色的最简单的代码。注:放入(本练习册)

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
ActiveSheet.Unprotect "Password"
Sh.UsedRange.Interior.ColorIndex = 27   'change colorindex to select background color
Target.Interior.ColorIndex = 32         'change colorindex to select active cell color
ActiveSheet.Protect Password:="Password"
End Sub

If you don't use protected sheets remove

如果您不使用受保护的工作表,请删除

ActiveSheet.Unprotect "Password"

ActiveSheet.Protect Password:="Password"