逻辑:
- 定义一个
Public
变量来保存单元格的颜色
- 检查上述
Worksheet_Change
变量是否有任何值。如果是,则更改目标单元格的颜色。
- 完成上述操作后,将变量重置为 0
模块中的代码:
Public cellColor As Double
Function SHEETOFFSET(offset, Ref)
With Application.Caller.Parent
SHEETOFFSET = .Parent.Sheets(.Index + offset) _
.Range(Ref.Address).Value
'~~> Store the color in a variable
cellColor = .Parent.Sheets(.Index + offset) _
.Range(Ref.Address).Interior.ColorIndex
End With
End Function
工作表代码区域中的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim aCell As Range
On Error GoTo Whoa
Application.EnableEvents = False
For Each aCell In Target.Cells
If cellColor <> 0 Then aCell.Interior.ColorIndex = cellColor
Next
Letscontinue:
cellColor = 0
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
截图:
我的个人想法:
- 我首先不赞成该
SHEETOFFSET
函数,因为该公式实际上是指当前工作表中的一个单元格。任何更改(例如,删除该单元格)都会使您的公式出错
- 最好直接链接单元格
跟进(来自评论)
您可以在最后运行此代码以刷新所有公式。
Sub Sample()
Dim ws As Worksheet
Dim rng As Range, aCell As Range
For Each ws In ThisWorkbook.Sheets
Set rng = Nothing
On Error Resume Next
Set rng = ws.Cells.SpecialCells(xlCellTypeFormulas)
On Error GoTo 0
If Not rng Is Nothing Then
For Each aCell In rng
aCell.Formula = aCell.Formula
Next
End If
Next
End Sub