如果在excel中包含公式,如何在一个单元格中给出多种颜色

时间:2015-10-13 13:49:37

标签: excel excel-vba vba

我有一个公式

的单元格
="Average:"& AVERAGE(C2,C6)& "Items:"& SUM(C2,C6)

我需要"平均值"在那个细胞中为红色。保持黑色

1 个答案:

答案 0 :(得分:1)

要使用VBA解决方案执行此操作,您仍需要复制/粘贴特殊值>值,因为如果该单元格是公式,则无法仅为单元格的某些字符着色。

要将手动步骤包装到VBA子程序中,我们必须:

  1. 复制公式中的值并将其粘贴到新单元格中。
  2. 确定文本“Item:”的开始位置以及包含的字符数
  3. 在value'd单元格中绘制所需颜色的字符。
  4. (假设您的公式为D1)它看起来像:

    Sub avgSumColor()
        Dim rngFormulaCell As Range, rngValueCell As Range
        Dim itemStart As Integer, itemLength As Integer
    
        'Set the cell with the formula and the cell where we'll put the value
        Set rngFormulaCell = Sheet1.Range("D1")
        Set rngValueCell = Sheet1.Range("D2")
    
        'Copy/Paste special (just set the value of the valuecell to the value of the formulacell)
        rngValueCell.Value = rngFormulaCell.Value
    
        'Figure out where "Item:<number>" starts and
        '   how many characters long it is
        itemStart = InStr(1, rngValueCell.Value, "Items")
        itemLength = Len(rngValueCell.Value) + 1 - itemStart
    
        'set the first bit up to the text "Item:<number>" to red
        rngValueCell.Characters(1, itemStart).Font.Color = RGB(255, 0, 0)
    
        'set the last bit containing "Item:<number>" to black
        rngValueCell.Characters(itemStart, itemLength).Font.Color = RGB(1, 1, 1)
    End Sub