【问题标题】:Using VBA macro to process then remove html/xml tags使用 VBA 宏处理然后删除 html/xml 标签
【发布时间】:2021-09-02 13:38:47
【问题描述】:

我正在遍历单元格,试图将单元格值的某些部分加粗。我有一个包含内容的单元格:

<b>This part should be bold</b> but this should not be

我可以将正确的部分加粗,但下一步是删除标签。以下行会导致问题:

    Cells.Replace What:="<b>", Replacement:="", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
    Cells.Replace What:="</b>", Replacement:="", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

当这些行运行时(以任意顺序),整个单元格值变为粗体。更具体地说,在逐行运行之后,运行任何一行都会得到相同的结果。我是 VBA 新手,不确定是什么原因造成的。

我用来使子字符串加粗的函数是:

fCell.Characters(Start:=m, Length:=n - m + 1).Font.Bold = True

其中 fCell 被循环,m 和 n 分别是定位 的索引。

【问题讨论】:

    标签: excel vba formatting format


    【解决方案1】:

    一旦您只为单元格的部分内容设置了格式,您就无法在不丢失部分格式的情况下替换整个内容。

    您需要使用Characters 方法删除标签:使用Instr() 找到位置,然后将那里的文本设置为“”:

    Sub tester()
    
        RemoveStrings Range("A1"), Array("<b>", "</b>")
    
    End Sub
    
    Sub RemoveStrings(c As Range, Strings)
        Dim txt, pos As Long
        For Each txt In Strings
            Do
                pos = InStr(1, c.Value, txt, vbTextCompare)
                If pos > 0 Then c.Characters(pos, Len(txt)).Text = ""
            Loop While pos > 0
        Next txt
    End Sub
    

    【讨论】:

    • 出于好奇,我能否找到标签的位置,用我目前有缺陷的方法删除标签,然后最后进行部分格式化?
    • 如果你先去掉标签,你需要做跟踪哪些部分需要稍后格式化以及使用什么格式的工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2020-02-15
    相关资源
    最近更新 更多