在保持子字符串格式的同时操作字符串
Manipulating a string while keeping format of substrings
我想创建一个字符串,它是将字符“A”连接到现有字符串“JKLXYZ”的最后 3 个字符的结果。在此字符串中,“Y”为蓝色,其余为自动颜色。要获得的结果是“AXYZ”,其中“Y”仍为蓝色。
我想写:
Dim myString as String
myString = "A" & right(myString,3)
有两个问题希望得到帮助:
- 如何将 Word 文档中的原始字符串输入到 myString 变量中同时保持其格式 = 蓝色的“Y”?
- 假设我已经能够将带有蓝色“Y”的原始字符串输入到 myString 中,我该如何避免连接 and/or RIGHT 函数破坏格式(“Y”应该仍然是蓝色的)
非常感谢。
我制作了一些宏。 (注意:我不是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
注意:更改后的字符串将插入到找到的文本之后。
我想创建一个字符串,它是将字符“A”连接到现有字符串“JKLXYZ”的最后 3 个字符的结果。在此字符串中,“Y”为蓝色,其余为自动颜色。要获得的结果是“AXYZ”,其中“Y”仍为蓝色。
我想写:
Dim myString as String
myString = "A" & right(myString,3)
有两个问题希望得到帮助:
- 如何将 Word 文档中的原始字符串输入到 myString 变量中同时保持其格式 = 蓝色的“Y”?
- 假设我已经能够将带有蓝色“Y”的原始字符串输入到 myString 中,我该如何避免连接 and/or RIGHT 函数破坏格式(“Y”应该仍然是蓝色的)
非常感谢。
我制作了一些宏。 (注意:我不是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
注意:更改后的字符串将插入到找到的文本之后。