0

I wanted to create a string that is the result of concatenating the character "A" to the last 3 characters of an existing string "JKLXYZ". In this string the "Y" is blue, the rest is automatic colour. The result to obtain is "AXYZ" with the "Y" still in blue.

I wanted to write :

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

Two questions I would appreciate help with :

  1. How do I get the original string from the Word document into the myString variable while keeping its formatting = the "Y" in blue ?
  2. Assuming that I have been able to get into myString the original string with the "Y" in blue, how do I avoid the concatenation and/or the RIGHT function to destroy the format (the "Y" should still be in blue)

Thanks very much.

sbgib
  • 5,580
  • 3
  • 19
  • 26
nunof32
  • 1
  • 3
  • The color of a character is not a property of a string. It is something you have to set through some code in VBA. The string `myString` has no knowledge about colors. (But [Change color of certain characters in a cell](https://stackoverflow.com/questions/7618121/change-color-of-certain-characters-in-a-cell) could help you doing what you want to do ) – Luuk Dec 19 '20 at 11:34
  • Where are you trying to put this formatted set of characters? As @Luuk has said, a String does not maintain formatting but you can use a document Range and transfer formatted text to from one place to another. – Rich Michaels Dec 19 '20 at 13:02
  • @sbgib How do you know that this post is about `ms-word` ?? – Luuk Dec 19 '20 at 13:05
  • @Luuk: '1. How do I get the original string from the Word document'. – sbgib Dec 20 '20 at 07:50

1 Answers1

0

I crafted some macro. (note: I am not a VBA export!):

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

NOTE: The changed string will be inserted after the found piece of text.

Luuk
  • 12,245
  • 5
  • 22
  • 33