我正在尝试更改一个单元格(即活动单元格)的颜色,然后在单击另一个单元格(格式包括以前的字体,文本颜色,边框和单元格颜色)。 这是我用来更改单元格颜色的代码:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
Range("PrevCell").Borders.ColorIndex = 0
ActiveCell.Interior.ColorIndex = 3
With ActiveWorkbook.Names("PrevCell")
.RefersTo = ActiveCell
End With
End Sub
理想情况下,我需要的东西只能将单元格的颜色替换为更改前的颜色。
答案 0 :(得分:0)
您可以尝试这样的事情...
Dim prevCell As Range
Dim clr As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If prevCell Is Nothing Then
Set prevCell = Target
clr = Target.Interior.ColorIndex
Target.Interior.Color = vbRed
Else
prevCell.Interior.ColorIndex = clr
clr = Target.Interior.ColorIndex
Target.Interior.Color = vbRed
Set prevCell = Target
End If
End Sub
根据新要求进行编辑:
要在保存文件后从活动单元中删除红色,请进行以下设置...
在类似于Module1的标准模块上声明以下公共变量:
Public prevCell As Range
Public clr As Long
工作表模块代码:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If prevCell Is Nothing Then
Set prevCell = Target
clr = Target.Interior.ColorIndex
Target.Interior.Color = vbRed
Else
prevCell.Interior.ColorIndex = clr
clr = Target.Interior.ColorIndex
Target.Interior.Color = vbRed
Set prevCell = Target
End If
End Sub
此工作簿模块代码:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If Not prevCell Is Nothing Then prevCell.Interior.ColorIndex = clr
End Sub