From an subroutine in Excel, I am trying to create a header in a Word document with two words each with different font formatting however the last font formatting wins. Any help would be appreciated! Below is my current code snippet.
With myDoc.Sections(1).Headers(wdHeaderFooterPrimary).Range
.Font.Name = "Courier New"
.Font.Size = 10
.Font.Bold = True
.Font.Color = wdColorGreen
.text = "TEXT LINE 1" & vbLf
.Font.Name = "Calibri Light"
.Font.Size = 16
.Font.Bold = False
.Font.Color = wdColorBlack
.text = .text & "TEXT LINE 2"
....the rest of the code....
UPDATE: I solved the issue by explicitly setting the range. See code snippet below.
With myDoc.Sections(1).Headers(wdHeaderFooterPrimary).Range
.Start = 0
.text = "TEXT LINE 1" & vbLf
.End = Len(.text)
.Font.Name = "Courier New"
.Font.Size = 10
.Font.Bold = True
.Font.Color = wdColorGreen
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Start = Len(.text) + 1
.text = "TEXT LINE 2"
.End = Len(.text) + .Start
.Font.Name = "Calibri Light"
.Font.Size = 16
.Font.Bold = False
.Font.Color = wdColorBlack
This can be done a bit more efficiently / elegantly than the code posted in the "update". Relying on Start and End values is always a bit chancy with Word since Word can stick "hidden" content into the text flow. To get to the beginning or end of a Range it's more reliable to use Collapse. This will also be faster than doing calculations with values.
Dim rng as Word.Range
Set rng = myDoc.Sections(1).Headers(wdHeaderFooterPrimary).Range
With
'.Start = 0 'Not necessary as this will be the default position
.text = "TEXT LINE 1" & vbLf
'.End = Len(.text) 'Also not necessary, see further down...
.Font.Name = "Courier New"
.Font.Size = 10
.Font.Bold = True
.Font.Color = wdColorGreen
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Collapse wdCollapseEnd 'put focus at end of range
'.Start = Len(.text) + 1 'calculation not necessary as range has been collapsed
.text = "TEXT LINE 2"
'.End = Len(.text) + .Start 'not necessary
.Font.Name = "Calibri Light"
.Font.Size = 16
.Font.Bold = False
.Font.Color = wdColorBlack
End With
Related
I am trying to select all pages of a document except the 3 last ones. My final goal is to apply a style to text who have a specific font name and a specific font size. I am receiving an error message when running the code below about my 3rd code line : "object doesn't support this property or method". Any idea what this is about? Thanks!
Sub aHeadlines()
Dim V As Integer
Dim Z As Integer
V = ActiveDocument.Information(wdNumberOfPagesInDocument)
Z = 3
Dim rgePages As Range
Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=1
Set rgePages = Selection.Range
Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=V - Z
rgePages.End = Selection.Bookmarks("\Page").Range.End
rgePages.Select
With Selection.Find
.ClearFormatting
.Text = ""
.Font.Size = 10
.Font.Name = "Arial"
.Font.Bold = True
With .Replacement
.ClearFormatting
.Text = ""
.Style = ActiveDocument.Styles("Heading 1")
End With
.Execute Replace:=wdReplaceAll
End With
End Sub
Way simpler:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument
With .Range(0, .Range.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, _
Count:=.ComputeStatistics(wdStatisticPages) - 2).End - 1).Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Font.Size = 10
.Font.Name = "Arial"
.Font.Bold = True
.Replacement.Style = wdStyleHeading1
.Execute Replace:=wdReplaceAll
End With
End With
Application.ScreenUpdating = True
End Sub
Information is a property of the Range object, not Document.
V = ActiveDocument.Range.Information(wdNumberOfPagesInDocument)
NOTE:
It is rarely necessary to select anything when working with VBA. Using the Selection object slows down your code as the cursor moves with each change of the selection which means the screen has to be redrawn each time. Instead of Selection use the appropriate object for what you are trying to do, e.g. Range, Table, Shape, etc.
Your code can be rewritten using Range as below:
Sub aHeadlines()
Dim V As Integer
Dim Z As Integer
V = ActiveDocument.Range.Information(wdNumberOfPagesInDocument)
Z = 3
Dim rgePages As Range
Set rgePages = ActiveDocument.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=V - Z)
rgePages.End = rgePages.Bookmarks("\Page").Range.End
rgePages.Start = ActiveDocument.Range.Start
With rgePages.Find
.ClearFormatting
.Text = ""
.Font.Size = 10
.Font.Name = "Arial"
.Font.Bold = True
.Wrap = wdFindStop
With .Replacement
.ClearFormatting
.Text = ""
.Style = ActiveDocument.Styles("Heading 1")
End With
.Execute Replace:=wdReplaceAll
End With
End Sub
everyone.
I've only been immersed in the world of macros for a few days now and don't really know my way around.
I have several Word 2016 documents that I want to reformat. Each document has exactly the same structure (see attached file).
What I have done so far (and how it works)
Since the images are distorted and too large, I first set them in the same aspect ratio and reduce them to 50%.
Dim i As Long
With ActiveDocument
For i = 1 To .InlineShapes.Count
With .InlineShapes(i)
.ScaleHeight = 50
.ScaleWidth = 50
End With
Next i
End With
Then I search for the text lines "Slide notes" and replace them with the text "Speaker text:".
And also the text "Text Captions" I replace in the same way, with "Screen text:"
Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:="Slide notes", _
ReplaceWith:="Speaker text:", Replace:=wdReplaceAll
Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:="Text Captions", _
ReplaceWith:="Screen text:", Replace:=wdReplaceAll
And now I just can't get any further
Next, on each page, the text between "Speaker text" and "Screen text" should be filled into a table with two columns.
Ideally, the two columns should have a division of 2/3 to 1/3 (at full width).
At each line break, a new table line should be inserted
The table should end with the last entry (before "Screen text:")
This is the script, how I try to create the two-column table but unfortunately not working correctly.
Dim rng As Range
sTx = "Speaker text:"
With ActiveDocument
Set rng = .Range(.Characters(InStr(.Content, sTx) + Len(sTx) + 1).Start, .Characters(InStr(.Content, "Screen text:") - 1).End)
rng.Select
rng.ConvertToTable Separator:=wdSeparateByParagraphs, NumColumns:=1, _
NumRows:=2, InitialColumnWidth:=CentimetersToPoints(5), AutoFitBehavior _
:=wdAutoFitFixed
With rng.Tables(1)
.ApplyStyleHeadingRows = True
.ApplyStyleLastRow = False
.ApplyStyleFirstColumn = True
.ApplyStyleLastColumn = False
'Apply borders around table
.Borders(wdBorderTop).LineStyle = wdLineStyleSingle
.Borders(wdBorderBottom).LineStyle = wdLineStyleSingle
.Borders(wdBorderLeft).LineStyle = wdLineStyleSingle
.Borders(wdBorderRight).LineStyle = wdLineStyleSingle
End With
.Tables(1).Range.Columns.Add ' InsertColumnsRight
.Tables(1).Columns(1).SetWidth ColumnWidth:=184.05, RulerStyle:= _
wdAdjustFirstColumn
.Tables(1).Columns(2).SetWidth ColumnWidth:=99.2, RulerStyle:= _
wdAdjustFirstColumn
End With
Unfortunately, it doesn't work the way I want it to.
Only one table is created (on the first page)
Only one frame is visible (no subdivision)
There is always an empty row (table)
The table does not have the full widthe
Before / After
Try:
Sub Demo()
Application.ScreenUpdating = False
Dim i As Long
With ActiveDocument.Range
For i = 1 To .InlineShapes.Count
With .InlineShapes(i)
.ScaleHeight = 50
.ScaleWidth = 50
End With
Next i
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Slide notes*Text Captions"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
End With
Do While .Find.Execute
.Paragraphs.First.Range.Text = "Speaker text:"
.Paragraphs.Last.Range.Text = "Screen text:" & vbCr
.Start = .Paragraphs.First.Range.End
.End = .Paragraphs.Last.Range.Start
Do While .Characters.First.Text = vbCr
.Characters.First.Delete
Loop
With .Duplicate
.Find.Execute FindText:="^13^13", ReplaceWith:="^t^p", Replace:=wdReplaceAll
.ConvertToTable Separator:=vbTab, NumRows:=.Paragraphs.Count, NumColumns:=2, AutoFitBehavior:=wdAutoFitWindow
With .Tables(1)
.AllowAutoFit = False
.PreferredWidthType = wdPreferredWidthPoints
.Borders.Enable = True
.Rows(1).HeadingFormat = True
.Columns(1).SetWidth ColumnWidth:=.PreferredWidth * 2 / 3, RulerStyle:=wdAdjustProportional
Do While .Range.Characters.Last.Next = vbCr
.Range.Characters.Last.Next.Delete
Loop
End With
End With
.Collapse wdCollapseEnd
Loop
End With
Application.ScreenUpdating = True
End Sub
#macropod
May I ask you to explain your script to me.
The first part (the proportional reduction of the images) is clear so far.
Application.ScreenUpdating = False
Dim i As Long
With ActiveDocument.Range
For i = 1 To .InlineShapes.Count
With .InlineShapes(i)
.ScaleHeight = 50
.ScaleWidth = 50
End With
With the second section (replacing the two phrases), I already have more problems.
Next i
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Slide notes*Text Captions"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
End With
Do While .Find.Execute
.Paragraphs.First.Range.Text = "Speaker text:"
.Paragraphs.Last.Range.Text = "Screen text:" & vbCr
.Start = .Paragraphs.First.Range.End
.End = .Paragraphs.Last.Range.Start
Do While .Characters.First.Text = vbCr
.Characters.First.Delete
Loop
And I am hopelessly overwhelmed with the last part.
With .Duplicate
.Find.Execute FindText:="^13^13", ReplaceWith:="^t^p", Replace:=wdReplaceAll
.ConvertToTable Separator:=vbTab, NumRows:=.Paragraphs.Count, NumColumns:=2, AutoFitBehavior:=wdAutoFitWindow
With .Tables(1)
.AllowAutoFit = False
.PreferredWidthType = wdPreferredWidthPoints
.Borders.Enable = True
.Rows(1).HeadingFormat = True
.Columns(1).SetWidth ColumnWidth:=.PreferredWidth * 2 / 3, RulerStyle:=wdAdjustProportional
Do While .Range.Characters.Last.Next = vbCr
.Range.Characters.Last.Next.Delete
Loop
End With
End With
.Collapse wdCollapseEnd
Loop
End With
Application.ScreenUpdating = True
Please excuse me for inquiring. But I would like to understand the script.
Because I would also like to rewrite the script so that I can use it without the "Screen text:" section.
Thank you very much and best regards.
I want to change the format of some text that have font size = 20 and font name = "Times New Roman" to style of "Heading 1"
The issue is, for example the text is centered and doing manually when Heading 1 is selected the text is sent to left and changed its font size, font name and font color
to those that Heading 1. Then, once the text is related with "Heading 1" I can centered again and set the same format options as before and the text remains related with "Heading 1"
I tried to make this with VBA in order to applyt the same as above to all text with size 20 and font "Times New Roman", but my code below it seems to affect the other text within document
even that text has different font size.
How can I fix this problem?
Sub ChangeToHeading1()
Dim wdDoc As Document
Set wdDoc = ActiveDocument
With wdDoc.Range
.Find.ClearFormatting
.Find.Font.Size = 20
.Find.Replacement.ClearFormatting
.Find.Text = ""
.Find.Replacement.Text = ""
.Find.Replacement.Style = ActiveDocument.Styles("Heading 1")
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Font.Name = "Times New Roman"
.Font.Size = 20
.Find.Forward = True
.Find.Wrap = wdFindContinue
.Find.Format = True
.Find.MatchCase = False
.Find.MatchWholeWord = False
.Find.MatchWildcards = False
.Find.MatchSoundsLike = False
.Find.MatchAllWordForms = False
.Find.Execute Replace:=wdReplaceAll
End With
End Sub
Thanks in advance.
Since you haven't bothered to tell us what colour you want the Heading 1 Style to be, we can only guess. You really ought also spend a bit of time learning how to use VBA, not just the macro recorder - there are also innumerable examples of the kinds of code you need all over the web. For example:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument
With .Styles(wdStyleHeading1)
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Font.Name = "Times New Roman"
.Font.Size = 20
.Font.ColorIndex = wdGreen
End With
With .Range.Find
.ClearFormatting
.Text = ""
.Font.Size = 20
.Font.Name = "Times New Roman"
.Replacement.ClearFormatting
.Replacement.Text = ""
.Replacement.Style = wdStyleHeading1
.Format = True
.Forward = True
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
End With
Application.ScreenUpdating = True
End Sub
If I understand correctly you want Heading 1 to be in 20 point Times New Roman and centered. So just modify the style to have the settings you want before you apply it in your find.
Sub ModifyHeading1()
With ActiveDocument.Styles(wdStyleHeading1)
With .Font
.Name = "Times New Roman"
.Size = 20
End With
.ParagraphFormat.Alignment = wdAlignParagraphCenter
End With
End Sub
Sub ChangeToHeading1()
Dim wdDoc As Document
Set wdDoc = ActiveDocument
With wdDoc.Range.Find
.ClearFormatting
.Font.Size = 20
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Replacement.Style = ActiveDocument.Styles("Heading 1")
.Forward = True
.Wrap = wdFindContinue
.Format = True
.Execute Replace:=wdReplaceAll
End With
End Sub
I am using this code which specifically places the text in the precise cell I want using this code:
Dim myText1 As String
Dim myText2 As String
myText1 = "Header"
myText2 = "Body"
With ActiveDocument.Tables(1).Cell(2, 2).Range
.Font.Name = "Times New Roman"
.Font.Size = 12
.Font.Bold = True
.Font.Underline = True
.Text = myText1 & vbCr & vbCr & myText2
End With
The problem I am having is "myText2" is not supposed to be underlined or bold.
I have tried this:
Dim myText1 As String
Dim myText2 As String
myText1 = "Header"
myText2 = "Body"
With ActiveDocument.Tables(1).Cell(2, 2).Range
.Font.Name = "Times New Roman"
.Font.Size = 12
.Font.Bold = True
.Font.Underline = True
.Text = myText1 & vbCr & vbCr
.Font.Bold = False
.Font.Underline = False
.Text = myText2
End With
But what happens is the first myText1 gets deleted and all I am left with is myText2.
and this
With ActiveDocument.Tables(1).Cell(2, 2).Range
.Font.Name = "Times New Roman"
.Font.Size = 12
.Font.Bold = True
.Font.Underline = True
.InsertAfter myText1 & vbCr & vbCr
.Font.Bold = False
.Font.Underline = False
.InsertAfter myText2
While this appends the text, the formatting for the entire post is no underline or bold, when the end result is supposed to look like
Header
Body
How can I reformat myText2, have it post, without losing the formatted myText1 above?
In your code you have set the With statement to work with the entire range of the cell. This results in the formatting being applied to the entire cell.
You don't have to use the Selection object to apply formatting, you just need to make sure that you are working with the correct range. Using the Selection object makes the code run more slowly as it moves the cursor around.
I have rewritten your code below.
Sub AddTextToCell()
Dim myText1 As String
Dim myText2 As String
myText1 = "Header"
myText2 = "Body"
With ActiveDocument.Tables(1).Cell(2, 2).Range
.Text = myText1 & vbCr & vbCr & myText2
With .Font
.Name = "Times New Roman"
.Size = 12
.Bold = False
.Underline = False
End With
With .Paragraphs.First.Range.Font
.Bold = True
.Underline = True
End With
End With
End Sub
Normally it is better to enter text the way you do, without using Select, but when applying different formats to different parts of a cell I think you have to use it. I had to change the order of the formatting and step around a bit in the document to make it work:
Dim myText1 As String
Dim myText2 As String
myText1 = "Header"
myText2 = "Body"
With ActiveDocument.Tables(1).Cell(2, 2).Range
.Font.Name = "Times New Roman"
.Font.Size = 12
.Font.Bold = True
.Font.Underline = True
.Text = myText1 & vbCr & vbCr
End With
'Select the whole cell
ActiveDocument.Tables(1).Cell(2, 2).Select
'Move to the right
Selection.Collapse Direction:=wdCollapseEnd
'Move back to the left
Selection.MoveLeft wdCharacter, 1
'Add the text (using the myText1 format)
Selection.Range.Text = myText2
'Select the on word the right (myText2)
Selection.MoveRight wdWord, 1, True
'Format myText2
Selection.Range.Font.Underline = False
Selection.Range.Font.Bold = False
I am trying to set up a new table at the end of my document and format it to my specifications. But the backgroundcolor and the textcolor do not seem to work. The Font size also is not exactly what I want, since it applies to the whole table and not only one cell.
This is what I have so far:
Dim myRange As Object
Set myRange = ActiveDocument.Content
myRange.Collapse Direction:=wdCollapseEnd
ActiveDocument.Tables.Add Range:=myRange, NumRows:=3, NumColumns:=2
With .Tables(.Tables.Count)
.Cell(1, 1).Select
With Selection
.Shading.Texture = wdTextureNone
.Shading.ForegroundPatternColor = wdColorWhite
.Shading.BackgroundPatternColor = wdColorGray25
.Font.Size = 14
.Font.Bold = True
.Text = "Hello World"
End With
End With
I want the first row of the table without borders and with font 14, bold, white text on gray background.
I found the Answer.
The solution is as follows:
With .Tables(.Tables.Count)
With .Cell(1, 1)
.Shading.BackgroundPatternColor = wdColorGray50
With .Range
With .Font
.TextColor = wdColorWhite
.Size = 18
.Bold = True
End With
.Text = "Hello World"
End With
End With
End With
I removed the selection of the cell and used it directly. But the real thing was, the use of .Range when applying .Font and .Text