vba - 根据背景颜色计算excel中文本的实例

标签 vba excel excel-formula

sample excel

要求是一段代码,它可以计算字符串的实例,即(ABC,DEF,GHK),基于它们是否存在于彩色单元格中,并将结果放在下面的单元格中,如图所示。

有人可以请教吗?

我尝试了一个示例代码

Sub Color()

Dim varCounter As String
Dim color As Integer
Dim nocolor As Integer

Range("E5").Select
color= 0
nocolor= 0

      Do Until Selection.Value = ""
                  If Selection.Font.Color = RGB(255, 0, 0) Then
                   color= color+ 1
                     Else
                   nocolor= nocolor+ 1
                   End If
                   Selection.Offset(1, 0).Select
        Loop
  Range("E47").Select
  Selection.Value = no


  Range("E48").Select
Selection.Value = color

End Sub

这是一个非常简单的代码,它检查文本字体是否有颜色,但我找不到任何检查单元格背景颜色的东西。

我也尝试了 excel formula ,但是我只能搜索 text 和 count ,它不计算基于单元格的背景颜色。

最佳答案

这是一个简单的用户定义函数。您可以将其放在常规模块中。然后,您可以从它所在的工作簿中的任何工作表中调用它:

Public Function CountByColorAndText(rng As Excel.Range, SearchText As String, CountColored As Boolean) As Long
Dim cell As Excel.Range
Dim CellCount As Long

For Each cell In rng
    If cell.Value = SearchText Then
         If (cell.Interior.ColorIndex = -4142 And Not CountColored) Or _
           (cell.Interior.ColorIndex <> -4142 And CountColored) Then
            CellCount = CellCount + 1
        End If
    End If
Next cell
CountByColorAndText = CellCount
End Function

它需要三个参数:要评估的范围、要搜索的字符串以及您是否计算有色(或无色)单元格:

enter image description here

因此,在上面的 E 列中,公式为:
=CountByColorAndText($A$2:$A$13,$D3,FALSE)

在 F 列中,除了最后一个参数 CountColored 之外,它是相同的。是 TRUE .

我不写很多用户定义的函数,所以有人可能会过来指出问题或改进。

关于vba - 根据背景颜色计算excel中文本的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14227250/

相关文章:

excel - 从html中获取属性字符串值

excel - 通过 MailEnvelope 发送电子邮件

vba - Excel VBA Application.Match错误处理和消息传递

excel - VBA Excel : Compile Error: Object required?

vba - Excel - 使用 VBA 插入公式

xml - xml功能区代码中的 "getPressed"和 "onAction"按钮属性有什么区别?

vba - CreateObject ("Excel.Application") .Workbooks.Open 和 Workbooks.Open 之间的区别

excel - 如何在excel VBA中引用命名表列?

Excel 筛选公式/函数 - 从筛选公式/函数返回第一行

vba - 在列表中查找最接近指定日期的前一个日期