Reputation: 787
I have an issue where there are randomly spaces in a word document that do not have the same format font and I'm trying to find a way to change the font to the font surrounding it.
I found some VB that I've tested that selects the text and replaces it with colored text:
Sub ChangeFont()
With ActiveDocument.Content.Find
.ClearFormatting
.Text = " "
Dim fontName As String
fontName = "Calibri"
With .Replacement
.ClearFormatting
.Font.Name = fontName
End With
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Sub
Now I'm trying to identify a way to instead of replacing the font text and color, get the font of the character before it and apply the font that exists on that character. Is there a way to get the index value and just pull the font name into the replace command? Is there an easier way to do this?
Ideally I'd like to be doing this in powershell but the above code works in VB but when I tried to adapt it, I clearly screwed something up so I'm just trying to make functional code before I adapt it... This is the powershell I tried to build:
$app = New-Object -ComObject Word.application
$app.Visible = $True
$doc = $app.Documents.Open($FileName,$null) #Open FileName, ConfirmConversions , ReadOnly -1 = MSOTrue
$Content = $doc.Content.Find
$Content.ClearFormatting
$Content.Text = " "
$Content.Replacement.ClearFormatting
$Content.Replacement.Text = "TEST"
$Content.Replacement.Font.Name = "Georgia"
$Content.Forward = -1 #true
$Content.Wrap = 1 #wdFindContinue
$Content.Format = -1
$Content.MatchCase = 0 #false
$Content.MatchWholeWord = 0
$Content.MatchWildcards = 0
$Content.MatchSoundsLike = 0
$Content.MatchAllWordForms = 0
$Content.Execute.Replace("2") #wdReplaceAll
$doc.Close() | out-null
$app.Quit() | out-null
Upvotes: 0
Views: 130
Reputation: 36342
There's no need to replace anything, just find each space, and set it's font to be that of the character before its' font.
$Word = New-Object -ComObject Word.Application
$Doc = $Word.Documents.Open($FilePath)
$DocFind = $Doc.Content.Find
Do{
$DocFind.ClearFormatting()
$DocFind.Text = " "
$NextSpace = $DocFind.Execute()
$DocFind.Parent.Font = $DocFind.Parent.Previous(1,1).Font
}Until(!$NextSpace)
That finds the first space in the document, and sets its font to be whatever the font was of the character before it, then it tries to find the next space. It does that until it can't find another space.
Upvotes: 1