【问题标题】:Format and Color Text in Excel Between Certain SubStringsExcel中某些子字符串之间的格式和颜色文本
【发布时间】:2018-12-24 02:47:51
【问题描述】:

我想在 excel 中突出显示一些文本(使其变为红色和粗体)。这应该在某些条件下使用公式自动完成。 文本格式如下:

<file size="99999" index="0" tid="2893892389283">picture.jpg</file><file size="65444557" index="0" tid="5636346466">movie.avi</file><file size="12135" index="0" tid="43743766433">textfile.txt</file>

所有这些东西都在一个单元格中。现在我想突出显示“size=”后面的数字和文件名。例如,在第一个字段中,我想将 99999 和 pictures.jpg 设置为红色和粗体。

我的 excel 文档中有很多这种格式的文本,唯一的方法就是自动生成。

这是一个例子。右侧是我需要的结果:

【问题讨论】:

  • 它需要VBA,因为公式不能改变任何单元格的格式。

标签: vba excel formula highlight


【解决方案1】:

正如@ScottCraner 在 cmets 中提到的,这是无法通过公式实现的。然而, 的选择是无限的。

这样就完成了50%的“任务”:

Public Sub FormatAndColor()

    Range("B1") = Range("A1")

    Dim lookFor As String: lookFor = "size="""
    Dim i As Long
    Dim lenLookFor As Long: lenLookFor = Len(lookFor)

    For i = 1 To Len(Range("B1"))
        With Range("B1")
            If .Characters(i, lenLookFor).Text = lookFor Then
                While IsNumeric(.Characters(i + lenLookFor, 1).Text)
                    With .Characters(i + lenLookFor, 1).Font
                    .Bold = True
                    .Color = vbRed
                    End With
                    i = i + 1
                Wend
            End If
        End With
    Next i

End Sub

这就是代码的作用:

  • 将输入从 A1 复制到 B1:
  • 循环遍历当前字符串的每个字符
  • 如果发现 String 和下一个 N 字符串等于 size=",则进入新循环。
  • 在新循环中,如果每个数字字符都加粗并着色

对于其他 50% 的“任务”,您可以应用类似的逻辑 - 查找 &gt; 并为其着色,直到找不到下一个打开标记。请注意不要使用最后一个&gt; 进入无限循环。这就是i &lt; Len(Range("B1")) 存在的原因:

Public Sub FormatAndColor()

    Range("B1") = Range("A1")

    Dim lookFor As String: lookFor = ">"
    Dim i As Long
    Dim lenLookFor As Long: lenLookFor = Len(lookFor)

    For i = 1 To Len(Range("B1"))
        With Range("B1")
            If .Characters(i, lenLookFor).Text = lookFor Then
                While .Characters(i + lenLookFor, 1).Text <> "<" And i < Len(Range("B1"))
                    .Characters(i + lenLookFor, 1).Font.Bold = True
                    .Characters(i + lenLookFor, 1).Font.Color = vbRed
                    i = i + 1
                Wend
            End If
        End With
    Next i

End Sub

最后,如果你将这两个循环结合起来并确保更新lookForlenLookFor,你会得到你需要的:

【讨论】:

  • @Gary'sStudent - 现在或多或少是一种爱好 :)
  • 非常感谢。什么是迭代抛出一整列的好方法?因此,例如从 A1 到 A25(直到到达列的末尾)
  • @J.Doe - 如果您提出新问题 - 提出新问题,请勿编辑。
猜你喜欢
  • 2012-12-16
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2011-06-05
相关资源
最近更新 更多