How to use VBA to convert text in Microsoft Word - vba

I want all our old Word documents at the Uni to start to have accessible styles applied. For this test, I want to set up a macro to search a Word doc and wherever it finds 11pt Arial, I want it to apply an Accessible Style which will be Verdana 11pt. In doing this, it means academic staff could more easily convert non-accessible documents into more accessible documents.
I've started learning macro and can create one which saves the Word file out to PDF, which is a useful shortcut but I'm struggling.
I've tried creating a macro to open Replace, look for any instances of Arial 11pt and then replace them all with another style, but when I run it, it seems to apply my alternative style but also adds weird boxes to the document.
Also, if I apply the Header Style to the doc and then manually edit that style to be Arial 11pt then when I run the macro, the text seems to get the new Style applied but what I see is still Arial, and I get the weird boxes!
I would love to crack this on my own but it's not an area I am familiar with so any help from the community would be fantastic.
Here's the macro code, which I created using the recorder:
Sub Style()
'
' Style Macro
'
Selection.Find.ClearFormatting
With Selection.Find.Font
.Size = 11
.Bold = False
.Italic = False
End With
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Style = ActiveDocument.Styles("Written Stuff")
With Selection.Find.Replacement.ParagraphFormat
With .Shading
.Texture = wdTextureNone
.ForegroundPatternColor = wdColorBlack
.BackgroundPatternColor = wdColorBlack
End With
.Borders.Shadow = False
End With
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
In this example, instead of using Verdana I'm using Algeria so I can more easily see the font changes.

You are looking for a text attribute Font="Arial 11pt" and then want to apply a Paragraph style. Probably attributes applied to text of a paragraph have a higher priority than the attributes of the style of the parapgraph.
When you say "Also, if I apply the Header Style to the doc and then manually edit that style to be Arial 11pt then..." you are NOT manually editing the style but are editing the text of a pragraph that has a style. (Editing the style would mean editing the definition of the style, and the style can have been applied to many paragraphs).
You can do two things:
Replace the text-level font with the text-level new font, or
Remove the text-level font attribute and apply the paragraph style.

Related

Adjusting the width of columns of all tables in a Word document

In my Word document, I have over 300 tables and I want to change the table style and adjust the columns' widths. I am using the following code in my VBA macro. It's working for a style but not for column width. Please help me find where the problem is.
Sub Makro1()
'
' Makro1 Makro
'
'
Selection.Find.ClearFormatting
With Selection.Find
.Text = "Variable"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveRight Unit:=wdCharacter, Count:=4, Extend:=wdExtend
Selection.Tables(1).Style = "eo_tabelle_2"
With Tables(1).Spacing
.Item(1) = 5.5 'adjusts width of text box 1 in cm
.Item(2) = 8.5 'adjusts width of text box 2 in cm
.Item(3) = 7.5 'adjusts width of text box 3 in cm
.Item(4) = 1.1 'adjusts width of text box 4 in cm
End With
End Sub
I'm going to interpret your question literally: that you merely want to process all the tables in the document and that your code is using Find only in order to locate a table...
The following example shows how you can work with the underlying objects in Word directly, rather than relying on the current Selection, which is what the macro recorder gives you.
So, at the beginning we declare object variables for the Document and a Table. The current document with the focus is assigned to the first. Then, with For Each...Next we can loop through each Table object in that document and perform the same actions on each one.
In this case, the style is specified and the column widths set. Note that in order to give a column width in centimeters it's necessary to use a built-in conversion function CentimetersToPoints since Word measures column width in Points.
Sub FormatTables
Dim doc as Document
Dim tbl as Table
Set doc = ActiveDocument
For Each tbl in doc.Tables
tbl.Style = "eo_tabelle_2"
tbl.Columns(1).Width = CentimetersToPoints(5.5)
tbl.Columns(2).Width = CentimetersToPoints(8.5)
tbl.Columns(3).Width = CentimetersToPoints(7.5)
tbl.Columns(4).Width = CentimetersToPoints(1.1)
Next
End Sub
As far as I can recall all the tables in a word file are a part of Tables collection and we can access the individual table item using an index. Assuming that you wont know the number of tables, here's the code that works for me.
For Each tbl In Doc.Tables
tbl.Columns(3).Width = 40
Next

Word VBA: Convert Superscripts in Footers/Headers

I'm using code like this to output all the headers/footers per section to a text file:
Word VBA - getting text file output to look right
I've been able to convert all the special characters in the sHeader/sFooter string variables using Replace() without a problem.
Example: sFooter = Replace(sFooter, ChrW(8804), "^R'\ {\uc2\u8804 <=}'")
All is great until I try to replace a superscript. Alt+x only gives me the value of the letter itself. I've tried looking up the hex value (may not even be a thing) with no success. I've even tried the different Latin character values.
I recorded a macro to see how Word would replace it and got:
Selection.Find.ClearFormatting
With Selection.Find.Font
.Superscript = True
.Subscript = False
End With
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "A"
.Replacement.Text = "^super{a}"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
The problem is I don't know how to use them together.
I tried to use oSec.Footers(wdHeaderFooterFirstPage).Range.Find... instead of Selection.Find... but that results in a null string.
Can I make a String object somehow from sHeader/sFooter so I can utilize the recorded macro code? I tried googling, converting string to object, but didn't get anything help. Is there a better approach?
Thanks in advance.
I know this isn't exactly answering your question, but the problem is that the character is the same regardless of whether it is superscript or not, i.e. superscript is formatting, just like bold or italics.
For example, a bold A, a normal A and a superscript A all have code 65.
If you are saving to a text file, you won't be able to save formatting, so you would need to invent your own representation for a superscript character.
The representation from the Find/Replace code, i.e. "^super{a}" is what Word uses to allow you to do Find/Replace on text with a specific formatting.
Note: There are some special characters such as ² which have a separate character code to 2, so these would have a different code.
Thank you M1chael for your input.
I was able to get the recorded macro above to work by setting the selection to the current header/footer section.
Example:
oSec.Footers(wdHeaderFooterPrimary).Range.Select
Selection = ActiveDocument.ActiveWindow.Selection
Thanks

Programmatically change a certain font+size to a different font+size

I have a ms-word document where Helvetica 13.5 is the main font for paragraphs. Unfortunately, it's not tied to any particular pre-defined style in the document (the text was copied into the document from a website). Additionally, you will see embedded in the paragraphs a few words italicized and some words which are 'Courier New'.
What I'd like to do is walk through the document looking for snippets of text that have a single font/size. If that text is Helvetica 13.5, I would like to change it to Times New Roman 12. I don't want to change the embedded courier new. Italicized words should stay italicized (but their font should change if it's Helvetica/13.5)
Is there an "easy" way to do this?
Thanks
I don't know how to do this programmatically, but I know Word has the ability to Find and Replace based on Formatting. Here is how you do it:
In your document for Windows do Ctrl-G, for Mac do Command-Option-G. This will pull up the Go To window.
Select the Replace tab
In the Replace tab you should see for Windows "More >>", for Mac a "v" (Down arrow). Hit that button, to pull up the extra functions.
Now choose the format you are looking for by hitting the format button at the bottom.
To choose the new format you want, select the "Replace with" text field and then do the same as the previous step. Your options should show up below the respective text field.
When ready, hit Replace All
Note: keep the text fields empty if you want the replace to only match text based on formatting
Sub Helv_to_TNR
With ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.Wrap = wdFindContinue
.format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Text = ""
.Replacement.Text = ""
.Font.Size = 13.5
.Replacement.Font.Size = 11
.Font.Name = "Helvetica"
.Replacement.Font.Name = "Times New Roman"
.Execute Replace:=wdReplaceAll
end with
end sub

vb.net highlight text in word

I am using VB.NET in VS 2012 Express to automate Word 2010.
I am trying to find a string and then highlight it in Turquoise. My code works to find and highlight it, but it does it in the default yellow color. How can I change that to the desired color?
I apologize if this is a silly question, I am teaching myself VB by writing this.
For x As Integer = 0 To (dateConnected.Count() - 1)
With oRng.Find
.MatchCase = False
.ClearFormatting()
.Text = dateConnected(x)
With .Replacement
.ClearFormatting()
.Text = dateConnected(x)
.Highlight = Word.WdColor.wdColorTurquoise
End With
.Execute(Replace:=Word.WdReplace.wdReplaceAll)
End With
Next
the Highlight property accept true or false,
the color index is determined by the DefaultHighlightColorIndex property, Which member Option property of application instance.
code:
ApplicationInstant.Options.DefaultHighlightColorIndex = Word.WdColorIndex.wdTurquoise
.Highlight = True

MS Word VBA: How to replace each word with its translation while keeping formatting

I have a word document and want to replace each single word with its translation while keeping all the formatting intact. I cannot use "Find And Replace" dialog because I am not trying replace a particular set of words but I am replacing all the words. How do I do that using VBA?
Update
I am using Word 2010. So far, I can loop through the words using ActiveDocument.Range.Words property but I don't know how to replace those words with its translation? While replacing, I want to keep all the formattings like font name, size, color, background color, underline, bold in short all the formatting options as it is.
I guess you have an array of words ("apple", "book", "cat") and the array of their translation ("pomme", "livre", "chat").
Your goal is to bulk change words one by one.
So you need a loop. Here is the loop that may help (if I understand your problem correctly).
Bulk change upon two arrays:
Option Explicit
Sub replaceArrayForArray()
'
'to create array use prefix\suffix and replacing tool http://textmechanic.com/
'
'
findArray = Array("apple", "book", "cat")
replArray = Array("pomme", "livre", "chat")
For i = 0 To UBound(findArray)
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = findArray(i)
.Replacement.Text = replArray(i)
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute replace:=wdReplaceAll
Next i
End Sub
The more diffucult issue could have been if you worked with figures and you had to bulk change figures without overlap. The method with the use of the same macro more or less described here: MS Word Macro to increment all numbers in word document.