Selection.Range not inserting my textbox at the cursor position - vba

I am writing a macro to insert a textbox containing a pre-formatted table into a Microsoft Word document, and I want it to insert the table at the current cursor location. With the current code I have, the textbox seems to be inserted at the beginning or end of the current page, instead of the cursor location.
Here is my code:
Sub InsertTable()
Dim shpTbox As Shape
Dim rngTbox As Range
Dim tblBox As Table
Set shpTbox = ActiveDocument.Shapes.addtextbox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=72, Top:=50, Width:=468, Height:=220, Anchor:=Selection.Range)
shpTbox.TextFrame.TextRange.Tables.Add Range:=shpTbox.TextFrame.TextRange, NumRows:=8, NumColumns:=4, _
DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
shpTbox.TextFrame.TextRange.Tables.Item(1).Select
shpTbox.TextFrame.TextRange.Tables(1).Style = ActiveDocument.Styles("Custom Table")
Selection.InsertCaption Label:="Figure", _
Title:=". Insert Caption Here", _
Position:=wdCaptionPositionBelow
shpTbox.Line.Visible = msoFalse
shpTbox.WrapFormat.Type = wdWrapSquare
shpTbox.WrapFormat.Side = wdWrapBoth
shpTbox.TextFrame.TextRange.ParagraphFormat.Alignment = wdAlignParagraphCenter
End Sub
Is there a way to do what I want to do? Can someone explain why this doesn't do what I want it to do?
Thank you!

Word positions to the page by default. You need to tell it otherwise, and re-set the Left and Top properties afterwards. After the TextBox has been inserted specify the relative horizontal and vertical positions. For example:
shpTbox.RelativeHorizontalPosition = wdRelativeHorizontalPositionColumn
shpTbox.RelativeVerticalPosition = wdRelativeVerticalPositionLine
shpTbox.Left = 72
shpTbox.Top = 50
You may want to test some of the WdRelativeHorizontalPosition and WdRelativeVerticalPostition enumeration values to see what works best for your situation.

Related

"Text Box Vertical Alignment" to "Middle" for a selected rows in PowerPoint through vba macro

I would like to create a macro which will change the "Vertical Alignment" to "Middle" of the selected rows/cells in a PowerPoint table. Can anyone pls help me with this.
Below example snapshot attached.
Below is the code. My code is perfectly working with the shape but could't work for the tables. pls assist.
ActiveWindow.Selection.ShapeRange.TextFrame2.VerticalAnchor = msoAnchorMiddle
To approach a table you can not use the Shape Object, but need to use Tables.
You can also format only Cell by Cell so you need to run a loop through all Rows and Columns
-----edited-----
To use the selected cells you have to iterate through all cells and see if they are selected
Sub SelectedCells()
Dim oTbl As table
Dim iIdx As Integer
Dim iIdy As Integer
Set oTbl = ActiveWindow.Selection.ShapeRange(1).table
For iIdx = 1 To oTbl.Rows.Count
For iIdy = 1 To oTbl.Columns.Count
If oTbl.Cell(iIdx, iIdy).Selected Then
With oTbl.Cell(iIdx, iIdy).Shape
.TextFrame.VerticalAnchor = msoAnchorTop
End With
End If
Next
Next
End Sub

Inserting AutoText as a row in MS Word using VBA

I am attempting to create an "Add Row" button in an MS Word 2016 form that will add another row to the bottom of a table that contains text content controls.
Simply adding a row doesn't include the content controls and copying a previous row will also copy over any text that has been added to those content controls, neither of which I want.
I read somewhere that it is possible to save an unpopulated row as AutoText, then insert the AutoText as a new row. I just am unable to find how to do this. I have the unpopulated row saved as AutoText, I just don't know how to add it to the bottom of the table using VBA.
Also, the form will be edit protected. The VBA code needed to unlock the form then relock it I already have. I am just leaving it off for right now while I attempt to figure this out.
I tried the below code, but keep getting a type mismatch error.
Private Sub AddInmate_Click()
ActiveDocument.Tables(2).Select
NormalTemplate.AutoTextEntries("Inmate_Row").Insert _
Where:=ActiveDocument.Tables(2).Range.Rows.Last
End Sub
Any help you all can provide is greatly appreciated.
The attempt is very close - it's trying to insert the new row "on top of" or "in" the last row. The trick is to get the table's Range then collapse it so that the target insertion point is immediately after the table. When table rows are pasted/inserted immediately after an existing table, inside the same paragraph mark, Word auotomatically incorporates them in the existing table.
Private Sub AddInmate_Click()
Dim tmpl As Word.Template
Dim rngTbl As Word.Range
Set rngTbl = ActiveDocument.Tables(2).Range
rngTbl.Collapse wdCollapseEnd
Set tmpl = NormalTemplate
tmpl.BuildingBlockEntries("Inmate_Row").Insert _
Where:=rngTbl, RichText:=True
End Sub
The approach I'd take is to use code like:
With Selection.Tables(1).Rows
'Insert an empty paragraph after our table, then replace it with a replica of the last row
With .Last.Range
.Next.InsertBefore vbCr
.Next.FormattedText = .FormattedText
End With
'Reset all content controls in the new last row
For Each CCtrl In .Last.Range.ContentControls
With CCtrl
If .Type = wdContentControlCheckBox Then .Checked = False
If .Type = wdContentControlRichText Or .Type = wdContentControlText Then .Range.Text = ""
If .Type = wdContentControlDropdownList Then .DropdownListEntries(1).Select
If .Type = wdContentControlComboBox Then .DropdownListEntries(1).Select
If .Type = wdContentControlDate Then .Range.Text = ""
End With
Next
End With
For a complete ContentControlOnExit macro implementing this in a situation analogous to yours, see: http://www.msofficeforums.com/word-vba/27809-code-add-new-row-table.html#post87989

Word VBA: ConvertToShape method makes image disappear

I wrote some code for a client which isn't working correctly on his machine (Win 10, Office 365) but is on mine (Win 10, Office 2016). The code inserts an image to the header then positions it and resizes it. I use the ConvertToShape method so I can access properties like width, height and position of the Shape class.
Dim pic As Shape
Dim shp As Word.InlineShape
Set shp = thisDocument.Sections.Item(1).Headers(wdHeaderFooterPrimary).Range.InlineShapes.AddPicture(fpImage) ' insert the image to the header
Set pic = shp.ConvertToShape ' THIS LINE CAUSES THE PROBLEM
The method causes the image to disappear. 'Pic' is still available and setting it's properties causes no error, but it is not visible. It's .visible property returns true.
Any ideas? Thanks.
Answer provided to cross-post at Microsoft Community
There is a way to do this with only an inline shape, by setting up a table to position the text on the left and the picture on the right. An additional advantage of this method is that, if you set the table's AutoFitBehavior property to wdAutoFitFixed and set the column width to the width you want for the shape, Word will automatically resize the picture to that width and keep the aspect ratio.
Here's a little sample macro:
Sub x()
Dim fpImage As String
Dim strExistingHeaderText
Dim tbl As Table
Dim shp As InlineShape
fpImage = "D:\Pictures\bunnycakes.jpg"
With ActiveDocument
strExistingHeaderText = _
.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text
Set tbl = .Tables.Add( _
Range:=.Sections(1).Headers(wdHeaderFooterPrimary).Range, _
numrows:=1, numcolumns:=2, _
AutoFitBehavior:=wdAutoFitFixed)
tbl.Columns(2).Width = InchesToPoints(1.5)
tbl.Columns(1).Width = InchesToPoints(5#)
tbl.Cell(1, 1).Range.Text = strExistingHeaderText
'tbl.Borders.Enable = False
Set shp = tbl.Cell(1, 2).Range.InlineShapes.AddPicture(fpImage)
End With
End Sub

Insert Symbol in Text box VBA Word

I have the following code to insert a textbox into a word document:
Sub mark()
Dim Box As Shape
Set Box = ActiveDocument.Shapes.AddTextbox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=20, Top:=20, Width:=20, Height:=20)
Box.TextFrame.TextRange.Text = "tick"
End Sub
The text inside the texbox needs to be:
Selection.InsertSymbol Font:="Wingdings", CharacterNumber:=-3844, Unicode :=True
I see you've found an answer, but there's a more optimal way to use the method you found. Since it's not possible to format code nicely in Comments I'm writing it up in the Answer space for you (and others who might have the same question). Also, the site prefers the useful information to be in an "Answer" since Comments tend to be over-looked or deleted...
In order to insert content from the Insert Symbol dialog box, use the InsertSymbol method, which applies to either the Range or the Selection`object.
Using the Rangeobject is always the preferred approach. In order to get a Range object for the text box content, adjust your code something like this:
Sub mark()
Dim Box as Word.Shape
Dim rngBox as Word.Range
Set Box = ActiveDocument.Shapes.AddTextBox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=20, Top:=20, Width:=20, Height:=20, _
Set rngBox = Box.TextFrame.TextRange
rngBox.Text = "tick"
rngBox.Collapse wdCollapseEnd 'focus at end of Range
rngBox.InsertSymbol Font:="Wingdings", CharacterNumber:=-3844, Unicode:=True
End Sub
The Collapse method allows you to continue adding text (optionally with formatting) for as long as you require...

How to write a VBA script to insert, move and text wrap an image

I am making a VBA script to generate default pages for my template document, it is all going well except for when I try to insert an image that is right aligned and text wrapped. I used VBA many years ago only for excel so am not sure how to structure the VBA script. I started making the VBA script for the image by itself to be later integrated which you can find below.
What I want to achieve with the VBA script
For it to insert an image from a file within the same directory as the template file (do I have to put the full path or can I put a truncated one to specify that it will always be in the same directory?)
For the inserted image to be square text wrapped (default distances)
For the image to be aligned with the left margin relative to the line I have inserted it in
The height of the image is at 200 x 150
Would you kindly be able to help elaborate on the MWE I have below. Thank you:
Sub Insert_picture()
'
' Insert_picture Macro
'
Dim imagePath As String
imagePath = "C:\Users\Edoardo\Documents\My Work\PhD\SkyDrive\Tutoring\Houria\Image Replacement.jpg"
ActiveDocument.Shapes.AddPicture FileName:=imagePath, _
LinkToFile:=False, _
SaveWithDocument:=True, _
Left:=-5, _
Top:=5, _
Anchor:=Selection.Range, _
Width:=200, _
Height:=150
With imagePath
.WrapFormat.Type = wdWrapSquare
End With
End Sub
I worked it out in the end as follows:
Sub Insert_SqWrap_Image()
Dim shp As Shape
Set shp = ActiveDocument.Shapes.AddPicture( _
FileName:="C:\Users\Edoardo\Documents\My Work\PhD\SkyDrive\Tutoring\Houria\Image Replacement.jpg", _
SaveWithDocument:=True, _
Anchor:=Selection.Range)
With shp
.WrapFormat.Type = wdWrapSquare
.Left = 246
.Top = 50
.Width = 250
.Height = 188
End With
End Sub