PDA

View Full Version : Search and replace text of a certain font



pmolsen
05-08-2023, 02:36 PM
I am trying to write an MS Word 2016 VBA macro that searches for certain text in Courier New font and changes it, using .Find and .Execute. It does not work. For some reason it does not set the .Font.Name property of the search text as specified. Here is the code:


test()
Dim selRange As Range
Set selRange = Selection.Range
With selRange.Find
.Text = "C"
.Font.Name = "Courier New"
Debug.Print "Search text " & .Text & " Font: " & .Font.Name & " Selected text: " & selRange.Text & ", Font: " & selRange.Font.Name
.Replacement.Text = "G"
.Execute Replace:=wdReplaceAll
Debug.Print .Found
End With
End Sub


Here is the text in the word document that I have selected. It is all in Courier New font: A B C

This is the output from the first debug line:
Search text C Font: Selected text: A B C, Font: Courier New

This is the output from the second debug line, indicating that it did not find any matching text:
False

pmolsen
05-08-2023, 03:03 PM
That is strange. I changed the code to Font.NameAscii = "Courier New" and it now works???