首页 > 解决方案 > 在保持子字符串格式的同时操作字符串

问题描述

我想创建一个字符串,它是将字符“A”连接到现有字符串“JKLXYZ”的最后 3 个字符的结果。在这个字符串中,“Y”是蓝色的,其余的是自动颜色。获得的结果是“AXYZ”,“Y”仍为蓝色。

我想写:

Dim myString as String
myString = "A" & right(myString,3)

我希望得到两个问题的帮助:

  1. 如何将 Word 文档中的原始字符串放入 myString 变量中,同时保持其格式 = "Y" 为蓝色
  2. 假设我已经能够使用蓝色的“Y”进入 myString 原始字符串,我如何避免连接和/或 RIGHT 函数破坏格式(“Y”应该仍然是蓝色的)

非常感谢。

标签: vbams-word

解决方案


我制作了一些宏。(注意:我不是 VBA 导出!):

Sub Macro1()
'
'
    Dim myString As String
    Dim myColor As Double
    myColor = -738131969
    
    ' Find something in myColor
    Selection.Find.ClearFormatting
    Selection.Find.Font.Color = myColor
    Selection.Find.Execute
    
    ' Select the word with the character in myColor
    Selection.MoveLeft Unit:=wdWord, Count:=1
    Selection.MoveRight Unit:=wdWord, Count:=1, Extend:=wdExtend
    
    ' check if the selected word contains "XYZ"
    If InStr(1, Selection.Text, "XYZ") > 0 Then
       myString = Selection.Text
       myString = "A" & Right(myString, 3)
       
       ' Insert the text after the current selection
       Selection.InsertAfter Text:=" " & myString
       Selection.MoveRight Unit:=wdWord, Count:=1
       
       ' Change the color of the "Y" to myColor
       Selection.MoveLeft Unit:=wdCharacter, Count:=2
       Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
       Selection.Font.TextColor = myColor
    End If
    
End Sub

注意:更改后的字符串将插入到找到的文本之后。


推荐阅读