首页 > 解决方案 > 使字符串中的多个但单独的字符变为粗体

问题描述

我有一个包含文本的单元格,如下所示:

k a2 d eu1 n - oe2 r gj y2 t lj e2 r i1 - t y1 r kj - jh e2 z aa1

最终应该是这样的:

k a2 d eu 1 n - oe2 r gj y2 t lj e2 r i 1 - t y 1 r kj - jh e2 z aa 1

为此,单元格的值存储在变量 v3 中。

Public Sub Guide()


Dim v3 As String
Dim i, j As Integer
Dim pos, pos1 As Long

v3 = Sheets("Script").Cells(12, 8).Value

i = 1
j = 0

Do
   j = InStr(i, v3, "1", vbTextCompare)
   i = j + 1


   pos = InStrRev(v3, " ", (j - 1))
   pos1 = (j - 1) - pos

 Call BoldText(v3, j - pos1, pos1)

Loop Until j = 0


End Sub

这就是我如何获得 1, 之前字母的位置,以及前一个空格和 1, ... (j - 1)之间的字符数pos1

这是“粗体字”:

Sub BoldText(Txt, strt As Integer, Lngt)
Dim Ln As Long

Ln = Len(Txt)



Range("H12").Select

With ActiveCell.Characters(Start:=1, Length:=(strt - 1)).Font
        .FontStyle = "Regular"
End With
With ActiveCell.Characters(Start:=strt, Length:=Lngt).Font
        .FontStyle = "Bold"
End With
With ActiveCell.Characters(Start:=(strt + Lngt + 1), Length:=(Ln - strt)).Font
        .FontStyle = "Regular"
End With


End Sub

所以这种方式可以保持字符1 to (one before the bold) 的常规字体。我们想要的那些会变得粗体,然后又是(one after bold) to End常规的。

如何通过多个实例来实现这一点,从而实现最终结果?

目前,在每个循环中,它都会重置最后一个。Excel 期望它的语法为1 to (x - 1)= 常规字体、x= 粗体字体、x + 1 to (y-1)= 常规、y= 粗体y + 1 to (z - 1)等……我只是不确定如何编写脚本。

提前谢谢了。如果您需要更清楚的内容,那么我可以尽力解释更多。

标签: excelformatvba

解决方案


这有点匆忙(而且有点 hack),但至少应该让你开始。它使用正则表达式。您可以将其中的一些转换为带有参数的子项。

Sub Regex2()

Dim oMatches As Object, i As Long, vOut

With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = "\s([a-z]+)1"
    Set oMatches = .Execute(Range("A1"))
End With

ReDim vOut(0 To oMatches.Count - 1, 1 To 3)

For i = 0 To oMatches.Count - 1
    vOut(i, 1) = oMatches(i).submatches(0)
    vOut(i, 2) = oMatches(i).firstindex
    vOut(i, 3) = oMatches(i).Length
Next i

For i = LBound(vOut) To UBound(vOut)
    Range("A1").Characters(vOut(i, 2) + 1, vOut(i, 3) - 1).Font.Bold = True
Next i

End Sub

推荐阅读