【问题标题】:VBA script to conditionally format specific text in a concatenated cell用于有条件地格式化连接单元格中的特定文本的 VBA 脚本
【发布时间】:2014-02-27 06:23:11
【问题描述】:

我是 Excel 新手,正在尝试编写 VBA 脚本来有条件地格式化某些单元格。

我有 A 列,每个单独的单元格看起来像这样。

项目名称:一号
AO:名字二
BO:三号
CO:名称四
DO:说出五个

一个额外的细节是,并非每个单元格都有全部五行。例如,一个单元格可能只有:

AO:名字二
BO:三号

我需要做的是格式化它,以便 Project Name:、AO:、BO:、CO: 和 DO: 都是粗体,而 Name One 是粗体、斜体和彩色的。我不知道如何在这里添加颜色,但它看起来像这样。

项目名称: 名字一(带颜色)
AO:名字二
BO: 三名
CO: 四名
执行: 五名

我想知道是否有办法创建一个 VBA 脚本来自动执行此操作?过去几天我的解决方法是单独选择每个单元格中的文本并在那里应用格式,这简直是地狱!

Excel 版本:2010

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    已编辑

    这对子程序将完成这项工作。格式可以一次应用于一系列单元格。

    ' Make a keyboard shortcut for this macro:
    Sub FormatActiveCells()
        Dim c As Range
        For Each c In Selection.Cells
            FormatCell c
        Next
    End Sub
    
    ' This subroutine does the work
    Sub FormatCell(c As Range)
        Dim pos1 As Integer, pos2 As Integer
        ' Determine if line 1 is project name
        pos1 = InStr(1, c.Text, "Project Name:")
        If pos1 > 0 Then
            ' Make "Project Name:" bold
            c.Characters(pos1, Len("Project Name:")).Font.FontStyle = "Bold"
            ' Advance past colon character
            pos1 = pos1 + Len("Project Name:")
            ' Find end-of-line character
            pos2 = InStr(pos1, c.Text, Chr(10))
            ' Make text between "Project Name:" and end-line italicized and colored
            c.Characters(pos1, pos2 - pos1).Font.FontStyle = "Bold Italic"
            c.Characters(pos1, pos2 - pos1).Font.Color = RGB(0, 0, 255)
            ' Point both positions to one character past end-of-line
            pos2 = pos2 + 1
            pos1 = pos2
        Else
            ' Point both positions to first character
            pos1 = 1
            pos2 = 1
        End If
    
        ' Format additional lines
        Do
            ' Find colon character
            pos2 = InStr(pos1, c.Text, ":")
            ' If not found, we're done
            If pos2 = 0 Then Exit Do
            ' Make text from start of line to colon bold
            c.Characters(Start:=pos1, Length:=pos2 - pos1).Font.FontStyle = "Bold"
            ' Find end-of-line
            pos2 = InStr(pos2 + 1, c.Text, Chr(10))
            ' If not found, we're done
            If pos2 = 0 Then Exit Do
            ' Point both positions to one character past end-of-line
            pos2 = pos2 + 1
            pos1 = pos2
            DoEvents
        Loop
    End Sub
    

    【讨论】:

    • 感谢您的回复!这对第 2-4 行非常有效,但在第一行,我实际上只希望“Name One”被斜体和着色(除了整行加粗)。此外,我希望能对缺失的行做出相应的反应 - 比如说,整个第一行都不存在,并且单元格以“AO:etc etc”开始。我不希望 AO 被着色/斜体
    • 昨晚我自己做了一个臃肿的宏来做这件事,但这个更简单,更聪明,像梦一样工作。非常感谢,先生。
    猜你喜欢
    • 1970-01-01
    • 2014-04-27
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多