我正在尝试扫描“A”列并将粗体字体应用于以三个空格开头然后继续使用任何其他字符的所有单元格。如果单元格字符串以四个或更多空格字符开头;不应对其应用粗体字体。
这就是我目前所拥有的;这会导致 A 列的所有单元格变为粗体。
Sub Macro1()
Dim regEx As New RegExp
NumRows = Range("A2", Range("A2").End(xlDown)).Rows.Count
regEx.Pattern = "(\s{3})(\S)"
regEx.Global = False
Sheets("1022_CPU").Activate
Range("A2").Activate
Application.ScreenUpdating = False
Do Until IsEmpty(ActiveCell)
If regEx.Test(ActiveCell.Value) Then
ActiveCell.Font.Bold = True
Else
ActiveCell.Font.Bold = False
End If
ActiveCell.Offset(1, 0).Activate
Loop
Range("A1").Select
Application.ScreenUpdating = True
End Sub
编辑: 示例数据:
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process()
org.apache.coyote.http11.Http11Processor.process()
org.apache.catalina.connector.CoyoteAdapter.service()
org.apache.catalina.core.StandardEngineValve.invoke()
考虑到上述数据,我想在第一行应用粗体字体(“org.”前面的三个空格,但不在其他三行上。这就是为什么构建诸如“LEFT”之类的函数函数将不起作用;因为它将在所有行上应用粗体字体。
最佳答案
which start with three spaces and then continue with any other characters.
我认为这个正则表达式模式符合您的标准:
regEx.Pattern = "^\s{3}.*$"
如果没有一些示例数据,很难判断 A 列中的所有单元格是否应该加粗。
顺便说一句,您不需要 If
block :
If regEx.Test(ActiveCell.Value) Then ActiveCell.Font.Bold = True Else ActiveCell.Font.Bold = False End If
regEx.Test(ActiveCell.Value)
是一个 bool 值,ActiveCell.Font.Bold
也是一个 bool 值 - 因此您可以将其分配给 regEx.Test
调用:
ActiveCell.Font.Bold = regEx.Test(ActiveCell.Value)
这不会解决您的问题,但看起来肯定更干净;)
也就是说,我认为您不需要 VBA,甚至不需要 RegEx 来执行此操作。尝试条件格式:选择 A 列,然后使用公式确定格式:=LEFT(A1,3)=""
,并将其设为粗体。 p>
考虑到提供的示例数据,您似乎分析/表述了错误的问题陈述:
which start with three spaces and then continue with
any other charactersnon-whitespace characters.
如果数据总是至少 4 个字符长,我不明白为什么条件格式方法不起作用:
=AND(LEFT(A1,3)=" ",MID(A1,4,1)<>" ")
将前 3 个字符为空格且第 4 个字符不是空格的行加粗。
关于regex - Excel VBA 正则表达式 : Format cell to Bold if starts with three spaces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27155303/