如何使用VBA将MS Word中的<strong> </strong>之间的所有文本变为粗体?

时间:2016-06-07 18:30:47

标签: vba ms-word word-vba

基本上我想将标签之间的文本转换为粗体。此文本将始终在评论中。目前的代码没有做任何事情。 我不确定这段代码是否有任何意义,但我通常使用VBA for Excel,而且单词似乎有点棘手。

Sub Bold()
    Dim eCom As Comment
    Dim iFound As Integer
    Dim rbold As Range
    Dim iDot As Integer
    Dim flag As Boolean
    Dim aDoc As Document
    Set aDoc = ActiveDocument
    flag = True
    Application.ScreenUpdating = False
    For Each eCom In ActiveDocument.Comments

        iFound = InStr(eCom.Range.Text, "<strong>")
        iDot = 0
        If iFound > 0 Then

            iDot = InStrRev(eCom.Range, "</") - iFound + 1
            Set rbold = aDoc.Range(Start:=eCom.Range.Start + iFound, End:=eCom.Range.Start + InStrRev(eCom.Range, "<"))
            rbold.Select
            Selection.Font.Bold = wdToggle
        End If

    Next eCom
    Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:1)

这里有一些问题。首先,似乎注释范围不使用与文档范围相同的编号。所以

 Set rbold = aDoc.Range(Start:=eCom.Range.Start + iFound, End:=eCom.Range.Start + InStrRev(eCom.Range, "<"))

实际上不是注释中的范围,而是文档中的范围,从注释中具有强html标记的位置开始。

其次,即使这是有效的,它也会在错误的地方开始加粗,从&#34;强&gt;&#34;

开始

第三,没有理由选择范围,只需将其设置为粗体。

这段代码会做你想要的(我注释掉了一行,因为我无法弄清楚它应该做什么):

Sub Bold()
    Dim eCom As Comment
    Dim iFound As Integer
    Dim rbold As Range
    Dim iDot As Integer
    Dim flag As Boolean
    Dim aDoc As Document
    Dim newCom As Comment
    Set aDoc = ActiveDocument
    flag = True
    Application.ScreenUpdating = False
    For Each eCom In ActiveDocument.Comments

        iFound = InStr(eCom.Range.Text, "<strong>")
        iDot = 0
        If iFound > 0 Then

            'iDot = InStrRev(eCom.Range, "</") - iFound + 1
            Set rbold = eCom.Range
            rbold.MoveEnd Unit:=wdCharacter, Count:=-(Len(rbold) - InStrRev(rbold, "</") + 1)
            rbold.MoveStart Unit:=wdCharacter, Count:=iFound + Len("<strong>") - 1
            rbold.Bold = True

        End If

    Next eCom
    Application.ScreenUpdating = True

End Sub