vba word: How to select images? - vba

So for my particular application, I want to be able to select an image after I've copied it in from Excel, and then insert a caption.
I can successfully copy images using:
docapp.Selection.Range.PasteSpecial DataType:=wdPasteEnhancedMetafile, Placement:=wdInLine
However, I'm having a lot of difficult just selecting the recently copied image so I can use
Selection.InsertCaption
What's the best way to select images?

Ok, I'm an idiot and have solved my own problem. It's not the prettiest code but it works:
The key is to use document.InlineShapes.Select:
Public Sub Chart2Word(chto As Chart, doc1 As Word.Document, docapp As Word.Application, _
Optional Title As Variant)
Dim objpic As Word.InlineShape
docapp.Activate
chto.CopyPicture
docapp.Selection.MoveEnd wdStory
docapp.Selection.Move
docapp.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
docapp.Selection.Range.PasteSpecial DataType:=wdPasteEnhancedMetafile, Placement:=wdInLine
doc1.InlineShapes(doc1.InlineShapes.Count).Select
Label = Me.Range("LabelName").value
If Not IsMissing(Title) Then
docapp.Selection.InsertCaption Label:=Label, Title:=": " + Title
End If

Related

Making links to Places in this document work in vba

I'm trying to make a VBA script that will take all the headings in a document and make a table of contents out of them, with hyperlinks to each of the headings. The headings are all found, parsed and all the hyperlinks are made, however they don't correctly reach their destination which is a place within the document. The default 'create hyperlink to Place in this document' code looks like this:
Selection.Range.Hyperlinks(1).Range.Fields(1).Result.Select
Selection.Range.Hyperlinks(1).Delete
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
SubAddress:="_Test_Heading"
Selection.Collapse Direction:=wdCollapseEnd
This is the code that you would get if you recorded a macro while using the 'Edit hyperlink' window.
Edit hyperlink window
The address field where normally there would be a URL is empty, while the subaddress field is filled by the name of the header with underscores.
I think the problem is that Word defaults to 'Existing file or web page' rather than 'Place in this document', even if 'Place in this document' were specified prior. If I switch the mode of a link to 'Place in this document' without changing the subaddress or anything else, it works - but having to go and do that for each link defeats the purpose of the script. I've been looking all over for a way to express 'Place in this document' in VBA but haven't found anything. Tried bookmarks as an alternative and that didn't work either. Any help would be appreciated.
I found a workaround using cross-referencing. In case it helps anyone in the future:
Private Function GetLevel(strItem As String) As Integer
Dim strTemp As String
Dim strOriginal As String
Dim longDiff As Integer
strOriginal = RTrim$(strItem)
strTemp = LTrim$(strOriginal)
longDiff = Len(strOriginal) - Len(strTemp)
GetLevel = (longDiff / 2) + 1
End Function
Sub TableofContents()
Dim i As Integer
Dim AllHeadings As Variant
AllHeadings = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading)
Selection.HomeKey Unit:=wdStory
Selection.HomeKey Unit:=wdLine
For i = LBound(AllHeadings) To UBound(AllHeadings)
strtext = Trim$(AllHeadings(i))
Level = GetLevel(CStr(AllHeadings(i)))
If Level = 2 Then
Selection.InsertCrossReference ReferenceType:="Heading", ReferenceKind:= _
wdContentText, ReferenceItem:=i, InsertAsHyperlink:=True, _
IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=" "
Selection.TypeParagraph
End If
Next
End sub
The first function gets the level of the heading.
The second part moves to the top of the document and starts inserting cross-references to the headings that I want (in this case I want it to be = 2).

VBA Picture Shadow Macro

I have a bunch of images that I would like to apply a specific picture style to - the 4th one that is shown in Word 2010:
I have a macro that will loop through all images, but need to know the possibilities for the shadow.type .
What would be really helpful is a reference to the commands that would be used for each type of picture style, with a visual example.
I don't have VBA, so can't examine the elements of the picture. I have tried various msoShadowxx, but that didn't work.
Is there a good reference with visual examples, or a reference with the settings for each picture style? Or the settings to use for the 4th picture style (shown in the screenshot here)?
Here is the macro code that I use to loop through all the pictures.
Sub BorderMacroshadow()
Dim oInlineShp As InlineShape
For Each oInlineShp In ActiveDocument.InlineShapes
With oInlineShp
.Line.Weight = 1
.Line.ForeColor.RGB = vbBlack
.Shadow.Type = msoShadow14
End With
Next
End Sub
Added
A closer look at the reference for msoShadow shows that it is referring to Picture Effects, Shadows 'dialog', not the 'Picture Styles', which I assumes uses some elements of msoShadow in addition to other elements.
So, I am looking for the elements that are needed to duplicate the 4th 'Picture Style' (see the screenshot). Haven't found those yet.
The msoShadowType enumeration is a group of pre-sets. These aren't necessarily used in the gallery on the Ribbon.
In order to ascertain the settings of any Shadows formatting use the various properties available for Shape.Shadow, such as Transparency, Size, Blur. Inthe UI, these can be seen in Picture Effects, Shadow, Shadow Options of the Picture Style group on the Ribbon.
To determine/set them programmatically, see the following code sample. Note that Angle is not one property, but a combintation of OffsetX and OffsetY.
Sub ShadowProperties()
Dim shp As Word.Shape
Dim shw As Word.ShadowFormat
Set shp = Selection.ShapeRange(1)
Set shw = shp.Shadow
With shw
Debug.Print "Blur: " & .Blur, _
"size: " & .Size, _
"Transparency: " & .Transparency, _
"Offset x: " & .OffsetX, _
"Offset y: " & .OffsetY
End With
End Sub

Select a VBA Pasted Shape from Excel to Word so I can wrap text tight

I'm developing a spreadsheet to automatically generate quotes; this involves copying the correct diagram (a grouped Excel shape) from a sheet with a library of our possible diagrams, and pasting/inserting/[whatever will work best] that image into the VBA-assembled Word document.
So far, I am able to successfully identify, copy and paste special the correct diagram shape from Excel into Word. However, every technique I have found means that the shape either wraps text as inline or infront-- whereas I need the next portion of text to be directly aside the diagram-- thus "wdTight"
Below, you can see how I paste in the current shape. But I can't figure out how to make that shape into ".wrapFormat.Type = wdTight"
I am generally met with a series of Runtime 438 errors: object doesn't support this property or method.
I have a theory that this is because Word considers the selection to always be the blinking text cursor, and not the just pasted shape which is activated and has a hovering layout options tooltip (but that is just a theory).
Here is the code. Please help.
Sub export_excel_to_word()
Dim appWord
Dim quoteWord
Dim wordSelection
Set appWord = CreateObject("Word.Application")
appWord.Visible = True
Set quoteWord = appWord.Documents.Add
Set wordSelection = appWord.Selection
'This part works
Module1.ImagesRefresh
'Product 1 image insertion
Sheets("Quick Lookup").Shapes("QuoteProduct1Image").Copy
wordSelection.PasteSpecial Link:=False, _
DataType:=wdPasteShape, _
Placement:=wdInLine, _
DisplayAsIcon:=False
'This part does not work and is where I need help
With wordSelection
.WrapFormat.Type = wdWrapFront
End With
Try creating a variable to represent the newly pasted shape, it should be accessible by index, and should be the last index:
'Product 1 image insertion
ActiveSheet.Shapes(1).Copy
wordSelection.PasteSpecial Link:=False, _
DataType:=wdPasteShape, _
Placement:=wdInLine, _
DisplayAsIcon:=False
Dim wdShape As Word.Shape
Set wdShape = quoteWord.Shapes(quoteWord.Shapes.Count)
wdShape.WrapFormat.Type = wdWrapTight
Without using the shape variable, this might also work, but I have not tested against a document with several shapes (assuming you're adding shapes in sequence/iteration)
'Product 1 image insertion
ActiveSheet.Shapes(1).Copy
wordSelection.PasteSpecial Link:=False, _
DataType:=wdPasteShape, _
Placement:=wdInLine, _
DisplayAsIcon:=False
wordSelection.ShapeRange(1).WrapFormat.Type = wdWrapTight
If you're also inserting text (e.g., through the TypeText method of a Word.Range, try the code below. I'm not super-familar with Word automation, and the rule that you should avoid activate/select I think is less strict in Word (or has more exceptions) but as a rule of thumb, I'd still try to avoid reliance on the Selection object, and work with ranges instead.
What I'm doing here is pasting to the wordSelection.Range rather than the Selection itself. Then I do
ActiveSheet.Shapes(1).Copy
wordSelection.Range.PasteSpecial Link:=False, _
DataType:=wdPasteShape, _
Placement:=wdInLine, _
DisplayAsIcon:=False
Dim wdShape As Word.Shape
Set wdShape = quoteWord.Shapes(quoteWord.Shapes.Count)
wdShape.WrapFormat.Type = wdWrapTight
wordSelection.TypeText "some text"

Word UserForm VBA: Hyperlink from Bookmark

I am able to populate a bookmarked location on a Word Document from user input via a UserForm.
What I would like to do is convert the text entered into a Hyperlink.
The following snippit of code was used to insert the text into the appropriate location:
Private Sub CommandButton1_Click()
Dim benchmarkURL As Range
Set benchmarkURL = ActiveDocument.Bookmarks("benchmark").Range
benchmarkURL.Text = Me.benchmarkURLTextBox.Value
ActiveDocument.Bookmarks.Add "benchmark", benchmarkURL
Me.Repaint
'Update the fields to populate the references of the bookmarks
UpdateAllFields
UserForm1.Hide
End Sub
I tried the following which did not work:
Private Sub CommandButton1_Click()
Dim benchmarkURL As Range
Set benchmarkURL = ActiveDocument.Bookmarks("benchmark").Range
benchmarkURL.Text = Me.benchmarkURLTextBox.Value
Hyperlinks.Add(ActiveDocument.Bookmarks.Add "benchmark", benchmarkURL)
Me.Repaint
'Update the fields to populate the references of the bookmarks
UpdateAllFields
UserForm1.Hide
End Sub
Any advice will be much appreciated
Thanks in advance
Hyperlinks.Add(ActiveDocument.Bookmarks.Add "benchmark", benchmarkURL)
There are at least two things wrong with this line, possibly more depending on what it is you want the hyperlink to link to.
You have omitted the parent object for the Hyperlink which should be ActiveDocument.
There should not be any brackets as the return value of
Hyperlinks.Add is not being assigned to anything.
You can find further info here: https://msdn.microsoft.com/en-us/library/office/ff837214(v=office.15).aspx
I found a better solution. For those that need, it is posted below:
'URL of Benchmark Data
Dim benchmarkURL As Range
Set benchmarkURL = ActiveDocument.Bookmarks("benchmark").Range
benchmarkURL.Text = Me.benchmarkURLTextBox.Value
ActiveDocument.Hyperlinks.Add Anchor:=benchmarkURL, Address:= _
benchmarkURL.Text, SubAddress:="", ScreenTip:="", TextToDisplay:= _
"Benchmark Data"
Just to provide some further description to Jame's answer.
'URL of Benchmark Data
Dim benchmarkURL As Range
Set benchmarkURL = ActiveDocument.Bookmarks("benchmark").Range
benchmarkURL.Text = Me.benchmarkURLTextBox.Value
ActiveDocument.Hyperlinks.Add Anchor:=benchmarkURL, Address:=benchmarkURL.Text, SubAddress:="", ScreenTip:="", TextToDisplay:="Benchmark Data"
means put this information in.
'URL of Benchmark Data
ActiveDocument.Hyperlinks.Add Anchor:=<<Where link will display>>, Address:= <<Where the link will go to>>, SubAddress:="", ScreenTip:="", TextToDisplay:="<<what the link text should say"
This is my working version. In my instance I take text like this AC-2 in a table cell and make a bookmark with AC2. One table with AC-2 clicks to another table with AC-2 that is bookmarked.
'/////////////
Set benchmarkURL = oDoc.Bookmarks(strText2).Range
With oDoc.Tables(r).Cell(i, 1)
.Range.Hyperlinks.Add Anchor:=oDoc.Tables(r).Cell(i, 1).Range, Address:="", SubAddress:=strText2, ScreenTip:="", TextToDisplay:=strText
End With

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...