Insert blank lines in a document before creating a table - vba

I am creating a table in a word document - but want to add 2 blank lines before creating the table. The code below creates the blank lines but I need to move the cursor (clear the selection) before creating the table. The code currently creates the tables on top of the 2 new blank lines.
I'm sure I'm missing one simple line of code :). Thanks for your help!
With ActiveDocument.Sections(1)
Selection.InsertParagraph
Selection.InsertParagraph
End With
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=2

1. method:
Selection.TypeParagraph
Selection.TypeParagraph
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=2
2. method:
Selection.InsertParagraph
Selection.InsertParagraph
Selection.EndKey Unit:=wdStory
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=2

Related

Run-time error 4198, command failed, when trying to set ms word doc to print view

I am trying to set the window view to printView.
I've used the "record macro" in word, to see how word suggests I set something to print view. Here's the code:
If ActiveWindow.View.SplitSpecial = wdPaneNone Then
ActiveWindow.ActivePane.View.Type = wdPrintView
Else
ActiveWindow.View.Type = wdPrintView
End If
Each time, the execution stops and gives me the above error. The debug points out:
ActiveWindow.View.Type = wdPrintView
as the buggy line. I've also tried:
If ActiveWindow.View.SplitSpecial = wdPaneNone Then
ActiveDocument.ActiveWindow.View.Type = wdPrintView
Else
ActiveWindow.View.SplitSpecial = wdPaneNone
ActiveWindow.View.Type = wdPrintView
End If
The issue seems to happen when the splitspecial is 4 (wdPanePrimaryFooter). But changing the conditional to account for that doesn't seem to work. If I comment out the view type line, everything goes fine.
Any ideas?
Thank you in advance.
Edit, here is the entire block, but I cannot replicate this error half the time:
Sub pageNumber()
ActiveDocument.Sections(ActiveDocument.Sections.Count) _
.Footers(wdHeaderFooterPrimary).Range.Select
With Selection
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.TypeText Text:="Page "
.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"PAGE ", PreserveFormatting:=True
.TypeText Text:=" of "
.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"NUMPAGES ", PreserveFormatting:=True
.Collapse
End With
ActiveDocument.Content.Select
Selection.Collapse wdCollapseStart
If ActiveWindow.View.SplitSpecial = wdPaneNone Then
ActiveDocument.ActiveWindow.View.Type = wdPrintView
Else
ActiveWindow.View.SplitSpecial = wdPaneNone
ActiveWindow.View.Type = wdPrintView
End If
End Sub
The kind of code in the question is the result of using the macro recorder. This tool is really great, but because it only mimics the user actions, the code it creates is sometimes not optimal. Working with headers and footers, especially, can make life more complicated than it ought to be... When code selects a header/footer range that triggers the display of the old Word 2.0 "panes" that were necessary for editing these. Word 6.0 introduced WYSIWYG and the panes were "retired" and only show up in this context.
When working with headers and footers a Range object is usually preferable than using Selection. You can think of a Range as a invisible selection, with the advantages: 1. It doesn't move the actual selection. 2. There can be as many Range objects as required for the task, while there can be only one selection.
The following code sample gets the Footer range and adds content to it. Since it never changes the selection, the screen is quieter and the pane never shows up (and the code is faster).
Working with ranges is relatively straight-forward, until field codes come into play. Then it takes a bit of work to get the "target" point for new material to follow a field.
Sub pageNumber()
Dim rngFooter As Word.Range
Dim fld As Word.Field
Set rngFooter = ActiveDocument.Sections(ActiveDocument.Sections.Count) _
.Footers(wdHeaderFooterPrimary).Range
With rngFooter
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Text = "Page "
.Collapse wdCollapseEnd
Set fld = .Fields.Add(Range:=rngFooter, Type:=wdFieldEmpty, Text:= _
"PAGE ", PreserveFormatting:=False)
End With
Set rngFooter = fld.result
With rngFooter
'Move the end of the range outside the field
.MoveStart wdCharacter, 1
.InsertAfter " of "
.Collapse wdCollapseEnd
.Fields.Add Range:=rngFooter, Type:=wdFieldEmpty, Text:= _
"NUMPAGES ", PreserveFormatting:=False
End With
End Sub

Word disappearing text

I am currently setting up some MS Word templates in Word 2010 and have encountered a problem, where text suddenly disappears at the end of a paragraph.
The problem only occurs in some specific scenarios, but I have experienced that it can be recreated in a lot of different ways. I have not, however, been able to pinpoint the exact reason why this happens. Therefore, I would like to find the specific reason, that makes the issue occur, in order to avoid it.
It seems that a combination of the existence of wrapped tables, content in the page header and a certain length of a line can invoke the issue.
To recreate a document where this issue occurs, please follow this procedure:
Open a new document in Word 2010.
Copy the code below into a new module in the VBA editor.
Run the A_ReplicateScenario macro to insert example content in the document.
Place the cursor at the end of line 3 (the line that ends close to the margin).
Type a new sentence after the dot, beginning with a space.
The text that you have typed, will disappear when the margin is reached.
The text will then be shown if for instance a character is deleted from the original text (i.e. from the beginning of the line) or if a formatting change is made (e.g. clear formatting). The 'Show all' setting in Word can also sometimes display the text, but will only display it while 'Show all' is activated. Other times Word will display 'ghosted' double lines which can not be selected.
A short video of the replicated issue can be viewed here: https://youtu.be/Bqp9STDRkXc
Sub A_ReplicateScenario()
Call SetUpNormalStyle
Call InsertBodyTextLines
Call InsertHeaderTextLines
Call InsertWrappedTables
Call SetUpMargins
Call InsertExampleBodyText
End Sub
Sub SetUpNormalStyle()
With ActiveDocument.Styles("Normal").Font
.Name = "Arial"
.Size = 10
End With
With ActiveDocument.Styles("Normal").ParagraphFormat
.SpaceAfter = 0
.LineSpacingRule = wdLineSpaceAtLeast
.LineSpacing = 12
End With
End Sub
Sub InsertBodyTextLines()
For i = 1 To 4
Selection.TypeParagraph
Next
End Sub
Sub InsertHeaderTextLines()
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
For i = 1 To 26
Selection.TypeParagraph
Next
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
Sub InsertWrappedTables()
Selection.HomeKey Unit:=wdStory
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
With Selection.Tables(1).Rows
.WrapAroundText = True
.HorizontalPosition = CentimetersToPoints(2)
.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
.VerticalPosition = CentimetersToPoints(4.5)
.RelativeVerticalPosition = wdRelativeVerticalPositionPage
End With
Selection.Tables(1).Columns(1).PreferredWidthType = wdPreferredWidthPoints
Selection.Tables(1).Columns(1).PreferredWidth = CentimetersToPoints(11)
Selection.MoveDown Unit:=wdLine, Count:=1
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
With Selection.Tables(1).Rows
.WrapAroundText = True
.HorizontalPosition = CentimetersToPoints(10)
.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
.VerticalPosition = CentimetersToPoints(8)
.RelativeVerticalPosition = wdRelativeVerticalPositionPage
End With
Selection.Tables(1).Columns(1).PreferredWidthType = wdPreferredWidthPoints
Selection.Tables(1).Columns(1).PreferredWidth = CentimetersToPoints(9)
End Sub
Sub SetUpMargins()
With ActiveDocument.PageSetup
.TopMargin = CentimetersToPoints(3.8)
.BottomMargin = CentimetersToPoints(2.8)
.LeftMargin = CentimetersToPoints(2.3)
.RightMargin = CentimetersToPoints(1.5)
End With
End Sub
Sub InsertExampleBodyText()
With Selection
.HomeKey Unit:=wdStory
.MoveDown Unit:=wdLine, Count:=3
.TypeText Text:="Ouwouwouwoiwoiuwoiuwoiuwoiuwoiuwoiuwoiw oiwu oiwu owiu woiu woiuw oiwu owiu owiu ww."
.TypeParagraph
.TypeText Text:="Woiuwoiuwoiuw."
End With
End Sub
The problem is related to the tables being formatted to float around the text. Word has a long history of issues with floating objects. And although Word has improved a lot over the years you might still experience problems, in particular with floating tables.
If you change the formatting of the second table (via Table Properties) and set the text wrapping to None, the bug goes away (YMMV).
My recommendation would be to avoid the floating tables if possible.

Word VBA - insert more than one type of text

To all,
I am trying to automate a Word document. To do this I want to insert some text. The normal code I would use (for a header) is:
Selection.TypeText Text:="This is Text"
Selection.Style = ActiveDocument.Styles("Heading 1")
However, I want to add multiple lines of different styles. So, I have the following code:
Sub createtest()
insertheading1 ("This is heading 1")
insertheading2 ("This is subheading 1")
End Sub
Function insertheading1(Text1)
Selection.TypeText Text:=Text1 & Chr(11)
Selection.Style = ActiveDocument.Styles("Heading 1")
End Function
Function insertheading2(Text1)
Selection.TypeText Text:=Text1 & Chr(11)
Selection.Style = ActiveDocument.Styles("Heading 2")
End Function
So, the intention is to add one line as a Heading 1 and then a second line as Heading 2 (a subheading). But what happens it that the second bit changes the first line so that they are both of the Heading 2 style.
Can anyone help?
Thanks.
Try this, for me, Word 2010 that's right.
You have to add a paragraph.
Function insertheading1(Text1)
Selection.TypeText Text:=Text1
Selection.Style = ActiveDocument.Styles(wdStyleHeading1)
Selection.TypeParagraph
End Function
Function insertheading2(Text1)
Selection.TypeText Text:=Text1
Selection.Style = ActiveDocument.Styles(wdStyleHeading2)
End Function

Insert two fields in Word 2010 page header using VBA

I am trying to insert two fields in a page header. I am able to insert them at the current selection (see code below), but I would prefer not having to select the page header before inserting the fields. Can this be done?
Sub insertFields()
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="DOCPROPERTY LastSavedTime ", PreserveFormatting:=True
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="FileName", PreserveFormatting:=True
End Sub
If you specify the section of the document to place the field in as well as the type of header (wdHeaderFooterPrimary, wdHeaderFooterFirstPage or wdHeaderFooterEvenPages) you can use this code:
Dim myRange As Range
Set myRange = ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range
ActiveDocument.Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="DOCPROPERTY LastSavedTime ", PreserveFormatting:=True
Additional Information in response to comment
You can use the Collapse method, which places the insertion point at the start or end position of a range, to insert multiple fields within the header. Add appropriate additional code to insert spaces, formatting or carriage returns:
myRange.Collapse wdCollapseEnd
ActiveDocument.Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="FileName", PreserveFormatting:=True

how to replace certain images (by name) to respective text in word by vba

i need to replace images in my word document by text like:
graphic1 -> text1
graphic2 -> text2
etc
Any ideas? is that possible?
So far best way was to go and find distictive properties of images (like height and width) and replace them as below:
Dim myShape As InlineShape
For Each myShape In ActiveDocument.InlineShapes
myShape.Select
ActiveWindow.ScrollIntoView Selection.Range
Select Case myShape.Width
Case "13,5"
Selection.Delete
Selection.TypeText Text:=" g1"
Case "8"
Selection.Delete
Selection.TypeText Text:=" g2"
Case "19,5"
Selection.Delete
Selection.TypeText Text:=" g3"
End Select
Next myShape