首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Excel VBA -财务模型颜色格式

Excel VBA -财务模型颜色格式
EN

Stack Overflow用户
提问于 2021-07-27 11:05:14
回答 1查看 601关注 0票数 0

在金融模型中,通常会根据单元格的输入来对其进行颜色编码(例如,请参见这里 )。我想为我创建一个自动执行此任务的宏。

所需的颜色代码如下

  • 蓝色:常量(文本除外)
  • 黑色:公式
  • 绿色:其他纸张的参考资料
  • 红色:对单独文件或外部链接的引用

由于罗里和塞缪尔的伟大回答,我能够通过以下代码实现上述目标:

代码语言:javascript
运行
复制
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只会更改包含常量或公式的工作簿中单元格的字体,并保持文本的整体格式不变。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-27 12:22:15

SpecialCells记录在这里:

https://learn.microsoft.com/en-us/office/vba/api/excel.range.specialcells

然而,并不是所有的事情都可以用它来完成。如果公式包含!],则它引用另一个工作表或文件。CleanStr删除引号中的所有文本,因为这些文本也可能包含这些字符。

代码语言:javascript
运行
复制
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是从这里开始采用的:删除字符串的两个特定字符之间的文本

代码语言:javascript
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68543731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档