在金融模型中,通常会根据单元格的输入来对其进行颜色编码(例如,请参见这里 )。我想为我创建一个自动执行此任务的宏。
所需的颜色代码如下
由于罗里和塞缪尔的伟大回答,我能够通过以下代码实现上述目标:
Sub financial_color_coding()
' Color hard-coded cells blue
With Selection.SpecialCells(xlCellTypeConstants, 21).Font
.Color = -65536 ' colour selected cells blue
.TintAndShade = 0
End With
' Select cells that contain formulas
Selection.SpecialCells(xlCellTypeFormulas, 23).Select
'Color selected cells based on their input
For Each cell In Selection
If Left(cell.Formula & " ", 1) = "=" Then
If InStr(CleanStr(cell.Formula), "]") Then
cell.Font.Color = RGB(255, 0, 0) ' red for references to other files
ElseIf InStr(CleanStr(cell.Formula), "!") Then
cell.Font.Color = RGB(0, 150, 0) ' green for references to other sheets
Else
cell.Font.Color = RGB(0, 0, 0) 'black for every other formula
End If
End If
Next cell
End Sub
Function CleanStr(strIn As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "\""[^)]*\"""
.Global = True
CleanStr = .Replace(strIn, vbNullString)
End With
End Function
运行marco只会更改包含常量或公式的工作簿中单元格的字体,并保持文本的整体格式不变。
发布于 2021-07-27 12:22:15
SpecialCells记录在这里:
https://learn.microsoft.com/en-us/office/vba/api/excel.range.specialcells
然而,并不是所有的事情都可以用它来完成。如果公式包含!
或]
,则它引用另一个工作表或文件。CleanStr
删除引号中的所有文本,因为这些文本也可能包含这些字符。
Selection.SpecialCells(xlCellTypeConstants).Font.Color = RGB(0, 0, 255) 'blue for constant
Selection.SpecialCells(xlCellTypeFormulas).Font.Color = RGB(0, 0, 0) 'black for formulas
'to be more specifiy
For Each cell In Selection
If Left(cell.Formula & " ", 1) = "=" Then
If InStr(CleanStr(cell.Formula), "]") Then
cell.Font.Color = RGB(255, 0, 0) ' red for references to other files
ElseIf InStr(CleanStr(cell.Formula), "!") Then
cell.Font.Color = RGB(0, 150, 0) ' green for references to other sheets
Else
cell.Font.Color = RGB(250, 0, 255) 'pink for formulars with output text
End If
ElseIf Not IsNumeric(cell.Text) Then
cell.Font.Color = RGB(0, 0, 0) 'black for text constant
End If
Next cell
CleanStr
是从这里开始采用的:删除字符串的两个特定字符之间的文本
Function CleanStr(strIn As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "\""[^)]*\"""
.Global = True
CleanStr = .Replace(strIn, vbNullString)
End With
End Function
https://stackoverflow.com/questions/68543731
复制相似问题