突出显示黄色的当前选择

时间:2015-07-29 18:19:03

标签: excel vba excel-vba

我只是希望所选范围为黄色,并在取消选择时返回无色。代码如下:

Option Explicit
Public previouscell As Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Selection.Interior.Color = vbYellow
    previouscell.Interior.ColorIndex = xlNone
    Set previouscell = Selection
End Sub

问题是首先设置previouscell。我尝试将它放在Worksheet_Activate()中,但是一旦我打开工作簿它就不会工作(只有当我更改了工作表时,它才会很好用。)

所以我尝试在ThisWorkbook.Workbook_open中宣布它为公众:

Option Explicit
Public previouscell As Range
Private Sub Workbook_Open()
    Set previouscell = ActiveCell
    ActiveCell.Interior.Color = vbYellow
End Sub

但它还没有认识到变量previouscell,因为我认为它不是从ThisWorkbook转移的(我在测试之前关闭并重新打开了工作簿)。有谁知道我需要为这个简单的任务改变什么?

4 个答案:

答案 0 :(得分:2)

如果将它放在相关工作表的代码模块中,这似乎有效。

Sub Worksheet_SelectionChange(ByVal Target As Range)
    Cells.Interior.ColorIndex = xlNone
    ActiveCell.Interior.Color = vbYellow
End Sub

答案 1 :(得分:2)

第4次修改

使用此工作簿代码,删除了工作表代码:

Option Explicit
Public previousCells As Range

Private Sub Workbook_Open()
    SetSelectionYellow
End Sub

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
    SetSelectionYellow
End Sub

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    SetSelectionYellow
End Sub

Private Sub SetSelectionYellow()
    If Not previousCells Is Nothing Then previousCells.Interior.ColorIndex = xlNone
    Set previousCells = Selection
    previousCells.Interior.Color = vbYellow
End Sub

答案 2 :(得分:1)

您使用第一个代码块进入了正确的轨道。只是测试是否已将previouscell设置为任何内容,如果没有,则将其设置为当前选择(或任何您想要做的事情)。

Option Explicit
Public previouscell As Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If previouscell Is Nothing Then
        Set previouscell = Selection
    End If

    Selection.Interior.Color = vbYellow
    previouscell.Interior.ColorIndex = xlNone
    Set previouscell = Selection
End Sub

答案 3 :(得分:0)

在ThisWorkbook.Workbook_Open子中,将previouscell设置为A1(或某些没有内部颜色的默认单元格)。然后在Worksheet_SelectionChange子中做你的事情。你有一切正确,但你需要2个部分:1)设置previouscell的初始默认值和2)当选择改变时改变单元格的内部。你做了第2部分,但错过了第1部分。