vba - 在保持子字符串格式的同时操作字符串
问题描述
我想创建一个字符串,它是将字符“A”连接到现有字符串“JKLXYZ”的最后 3 个字符的结果。在这个字符串中,“Y”是蓝色的,其余的是自动颜色。获得的结果是“AXYZ”,“Y”仍为蓝色。
我想写:
Dim myString as String
myString = "A" & right(myString,3)
我希望得到两个问题的帮助:
- 如何将 Word 文档中的原始字符串放入 myString 变量中,同时保持其格式 = "Y" 为蓝色?
- 假设我已经能够使用蓝色的“Y”进入 myString 原始字符串,我如何避免连接和/或 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
注意:更改后的字符串将插入到找到的文本之后。
推荐阅读
- php - 如何获取下拉列表值并插入 MySQL 服务器?
- onedrive - 有没有办法使用 google colab 从一个驱动器访问数据?
- docker - 如何使用 docker-compose 构建特定服务?
- sql - 如何使用 sql 将非英文日期字符串转换为英文格式
- r - 为什么 dea() 的输出与 dea.plot() (R 中的基准测试包)的(视觉)结果不匹配?
- merge - PowerBI如何合并两个不基于相同度量的数字
- python - 合并一个文件夹中的多个 PDFS,并将合并的 pdf 输出到另一个文件夹
- tsql - 如何在while循环中连接两个变量
- git - 将 Ubuntu 终端更改为 Window 的 Git-bash
- java - 是否可以将此日期字符串解析为 Date 而无需修改它?