突出显示黄色的当前select

我只是想要select的范围是黄色的,并且在取消select时返回到无色。 代码如下:

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中声明它为public:

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

但是它不能识别variablespreviouscell,因为我相信它不是从ThisWorkbook传输的(我在testing之前closures并重新打开了这个工作簿)。 有谁知道我需要改变这个简单的任务吗?

第四编辑

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

 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 

这似乎工作,如果你把它放在有问题的工作表的代码模块。

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

你在第一个代码块的正确轨道上。 只要testing看previouscell是否已经设置为任何东西,如果没有,将其设置为当前select(或任何你想要做的)。

 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 

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