Copy text and picture into new word document - vba

In the active word document I have a macro which extracts a text string and all images from the document.
I want to copy this text and the picture in a new blank word document.
I tried the following
Dim docNew As Document
Set docNew = Documents.Add
With ThisDocument
...
docNew.Content.Text = docNew.Content.Text & vbCrLf & sSentence
For Each iShape In .InlineShapes
iShape.Select
Selection.CopyAsPicture
docNew.Content.Paste
Next iShape
End With
When I execute this code, first the text is copied correctly to the new blank document. But when the picture is pasted, it overwrites the text and only the picture remains in the document.
How do I have to modify the code so that the text as well as all pictures are included?

As you would have discovered from looking at the help text .Content represents the whole of the main body of the document.
Assuming you want to add the pictures at the end of the document, replace
docNew.Content.Paste
with
With docNew.Content
.InsertParagraphAfter
.Paragraphs.Last.Range.Paste
End With

Related

VBA to add hyperlink to bookmark in MS-Word template

I need to add a hyperlink to a bookmark in an MS-Word template. The hyperlink (which changes depending on user input) points to an entry in a database on the web. I have no trouble building the hyperlink as a string variable, but I can't figure out how to put it in the bookmark so the user winds up with a Word document containing a link that can be clicked to go to the database entry. My code (below) just deletes the bookmark. What am I missing?
Dim databaseURL As String
' get databaseURL from an existing variable--this part works OK
databaseURL = ActiveDocument.Variables("databaseLink")
' put the hyperlink in a bookmark named "linkToDatabase"
Dim BMRange As Range
Set BMRange = ActiveDocument.Bookmarks("linkToDatabase").Range
BMRange.Text = "Database link"
ActiveDocument.Hyperlinks.Add Anchor:=BMRange, _
Address:=databaseURL, _
SubAddress:="", ScreenTip:="", TextToDisplay:=BMRange.Text
What you could do to simplify things is to have a bookmarked 'default' hyperlink field at the bookmarked range, then simply change the hyperlink field's code. For example:
ActiveDocument.Bookmarks("linkToDatabase").Range.Fields(1).Code.Text = "HYPERLINK " & databaseURL

Insert RichText (From RichTextBox, RTF File, OR Clipboard) into Word Document (Bookmarks or Find/Replace)

To summarize what I'm attempting to do, I work for a non-profit organization that sends out acknowledgement letters when someone donates money to us (a thank you, basically). We have multiple different letters that are written every month and sent to IS to "process". I would like to make this as efficient and use as little time as possible for IS, so I've created a program in VB.NET that takes content and pastes it into a template using Word bookmarks, updates a table in SQL so that the letter can be tested with live data, and sends an e-mail to the Production department letting them know to test the letter. It works fully, except...
I cannot for the life of me figure out how to retain RTF (RichText) when I insert the content into the letter template.
I've tried saving the content of the RichTextBox as an RTF file, but I can't figure out how to insert the RTF file contents into my document template and replace the bookmark.
I've tried using the Clipboard.SetText, odoc......Paste method, but it's unreliable as I can't accurately state where I'd like the text to paste. The find/replace function isn't very helpful because all of the bookmarks I'm trying to replace are within text boxes.
I'd show some code, but most of it has been deleted out of frustration for not working. Either way, here's some code I've been working with:
Private Sub testing()
strTemplateLocation = "\\SERVER\AcknowledgementLetters\TEST\TEMPLATE.dot"
Dim Selection As Word.Selection
Dim goWord As Word.Application
Dim odoc As Word.Document
goWord = CreateObject("Word.Application")
goWord.Visible = True
odoc = goWord.Documents.Add(strTemplateLocation)
Clipboard.Clear()
Clipboard.SetText(txtPreD.Rtf, TextDataFormat.Rtf)
odoc.Content.Find.Execute(FindText:="<fp>", ReplaceWith:=My.Computer.Clipboard.GetText)
'Code for looping through all MS Word Textboxes, but didn't produce desired results
For Each oCtl As Shape In odoc.Shapes
If oCtl.Type = Microsoft.Office.Core.MsoShapeType.msoTextBox Then
oCtl.TextFrame.TextRange.Text.Replace("<fp>", "Test")
goWord.Selection.Paste()
End If
Next
'Clipboard.Clear()
'Clipboard.SetText(txtPostD.Rtf, TextDataFormat.Rtf)
'odoc.Content.Find.Execute(FindText:="<bp>", ReplaceWith:="")
'goWord.Selection.Paste()
MsgBox("Click Ok when finished checking.")
odoc.SaveAs2("\\SERVER\AcknowledgementLetters\TEST\TEST.docx")
odoc = Nothing
goWord.Quit(False)
odoc = Nothing
goWord = Nothing
End Sub
...and here is the default code for setting bookmarks. This works perfectly as long as formatting is not required:
Private Sub SetBookmark(odoc As Object, strBookmark As String, strValue As String)
Dim bookMarkRange As Object
If odoc.Bookmarks.Exists(strBookmark) = False Then
Exit Sub
End If
bookMarkRange = odoc.Bookmarks(strBookmark).Range
If ((Err.Number = 0) And (Not (bookMarkRange Is Nothing))) Then
bookMarkRange.text = strValue
odoc.Bookmarks.Add(strBookmark, bookMarkRange)
bookMarkRange = Nothing
End If
End Sub
TL;DR - Need formatted text (Example: "TEST") to be inserted into a Word document either as a bookmark or as a replacement text.
Expected results: Replace "fp" (front page) bookmark with "TEST" including bold formatting.
Actual results: "fp" is not replaced (when using clipboard and find/replace method), or is replaced as "TEST" with no formatting.
I figured it out! I had to do it a weird way, but it works.
The following code saves the RichTextBox as an .rtf file:
RichTextBoxName.SaveFile("temp .rtf file location")
I then used the following code to insert the .rtf file into the bookmark:
goWord.ActiveDocument.Bookmarks("BookmarkName").Select()
goWord.Selection.InsertFile(FileName:="temp .rtf file location")
I then deleted the temp files:
If My.Computer.FileSystem.FileExists("temp .rtf file location") Then
My.Computer.FileSystem.DeleteFile("\temp .rtf file location")
End If

Convert Figure Alt Description to Picture Caption in Word

I need a way to get an image's Alt Description (specified in HTML) into the Word DOCX image's Caption. This needs to be done with many images in a document, so a macro would be best.
Assume an HTML doc with an img tag similar to this
<img src="http://www.example.com/path/to/image/picture01.jpg"
title="picture 01 title"
alt="this is alt text"
caption="this is a caption field">
This HTML doc is imported into Word 2010 (via File, Open). The image will show in the doc.
Now, how to get the 'title' attribute (which shows up in the Format Picture's Alt-Text dialog as the Description - see screenshot below) into the image's Caption?
Note that the caption parameter in the image tag is not converted to a Word Caption for that image.
Sample Alt-Text dialog for an image which shows the image's alt value as the Description
Microsoft Word has a Range.InsertCaption method, which will insert field codes to automatically number images. As you were asking to insert Alternative Text, my feeling is you were using the term caption simply as a directive to get the text beneath each image on its own carriage return. So that's what this code does:
Sub GenerateAltTextCaptions()
Dim AltTextCaption As String
Dim ImageRange As Range
Selection.GoTo What:=wdGoToSection, Which:=wdGoToFirst
With ActiveDocument
For i = 1 To .InlineShapes.Count
AltTextCaption = .InlineShapes(i).AlternativeText
Set ImageRange = .InlineShapes(i).Range
ImageRange.Collapse Direction:=wdCollapseEnd
ImageRange.InsertAfter vbCr
ImageRange.InsertAfter AltTextCaption
Next
End With
End Sub
Yes, I think you've hit on a good way to make the conversion. Glad you were able to find it!
The code below will loop all the InlineShapes in the document and, if the Alternative Text is not empty, create a caption using that text.
InsertCaption is only available in VBA for InlineShapes. The user can insert captions for Shapes (graphics with text wrap formatting) because Word evaluates the selected graphic and creates a Textbox of the same width and positions it immediately below the graphic. The Shape and textbox are not, however, linked together in any way. So this functionality is not offered in VBA and would require some "creative" programming.
Sub InsertCaptionFromAltText()
Dim doc as Word.Document
Dim ils As word.InlineShape
Dim captionText As String
Set doc = ActiveDocument
Set ils = doc.InlineShapes(1)
For each ils in doc.InlineShapes
captionText = ils.AlternativeText
If Len(captionText) > 0 Then
ils.Range.InsertCaption Label:=wdCaptionFigure, _
Title:=captionText, _
Position:=wdCaptionPositionBelow
End If
Next
End Sub

VBA: Replace text based on formatting

I have a table in a Word file A which contains a bunch of different Contents. Which I just copy using VBA into another Word or PowerPoint file B. So far that is not a problem.
However, since file A is a working sheet, people sometimes cross stuff out, which means: it should be removed, but for the record it stays in there first. In the final version it shouldnt be displayed, so in the process of copying everything in a different file, the crossed out text should be removed.
To break it down to the technical stuff:
I want to select text in a Word document, and then remove all text that has a certain formatting.
Maybe there is a special selection possibility or a way to iterate through all characters and test for formatting.
The best way to do this without suffering severe performance iterating characters or paragraphs in vba is to use find and replace.
You can do this in vba as follows, note I have wrapped all the actions in a custom undo record, then you can call your current vba routine with CopyDocumentToPowerPoint and the word document will be restored to the state it was before the macro ran (crossed out text remains in word, but is not pasted to powerpoint).
'wrap everything you do in an undo record
Application.UndoRecord.StartCustomRecord "Move to powerpoint"
With ActiveDocument.Range.Find
.ClearFormatting
.Font.StrikeThrough = True
.Text = ""
.Replacement.Text = ""
.Execute Replace:=wdReplaceAll
End With
'copy to powerpoint and whatever else you want
CopyDocumentToPowerPoint
Application.UndoRecord.EndCustomRecord
'and put the document back to where you started
ActiveDocument.Undo
It is possible to go character-by-character and remove those which have the strikethrough font enabled on them (the ones which are crossed out) in MS Word. However, as far as I know, there is no such possibility to detect a strike-through font in MS PowerPoint.
If you just need to delete the text which has the strikethrough font on it in the selected text only, you can use this Word macro:
Sub RemoveStrikethroughFromSelection()
Dim char As Range
For Each char In Selection.Characters
If char.Font.StrikeThrough = -1 Then
char.Delete
End If
Next
End Sub
If more integrated to copying a Word table to another Word document and PowerPoint presentation, the following code might be useful. It first pastes the table to a new Word file, then removes unnecessary characters, and after that pastes this new table to PowerPoint.
Sub CopyWithoutCrossedOutText()
Dim DocApp As Object: Set DocApp = CreateObject("Word.Application")
Dim PptApp As Object: Set PptApp = CreateObject("PowerPoint.Application")
Dim Doc As Object: Set Doc = DocApp.Documents.Add
Dim Ppt As Object: Set Ppt = PptApp.Presentations.Add
Dim c As Cell
Dim char As Range
DocApp.Visible = True
PptApp.Visible = True
'Copying Word table to the 2nd Word document
ThisDocument.Tables(1).Range.Copy
Doc.ActiveWindow.Selection.Paste
'In the 2nd Word document - removing characters having strikethrough font enabled on them
For Each c In Doc.Tables(Doc.Tables.Count).Range.Cells
For Each char In c.Range.Characters
If char.Font.StrikeThrough = -1 Then
char.Delete
End If
Next
Next
'Copying the table from the 2nd Word document to the PowerPoint presentation
Doc.Tables(1).Range.Copy
Ppt.Slides.Add(1, 32).Shapes.Paste
End Sub

Check Word 2007 bookmark content and do something if it exists

Is it possible to search the content inside a bookmark and if it exists, do something.
For example, if there is a word document with a bookmark named Bookmark1. The enclosing text for Bookmark1 was created by highlighting the the text "Entered Text Goes Here". I want to create a macro that will check to see if the text inside the bookmark was changed, and if NOT, delete the text, the bookmark, the section break before it.
The code below does this except that it deletes the bookmark even if the text is different because it is looking for the name of the bookmark, not its content.
If ActiveDocument.Bookmarks.Exists("Bookmark1") = True Then
ActiveDocument.Bookmarks("Bookmark1").Select
Selection.Delete
With Selection
.EndKey Unit:=wdStory
.TypeBackspace
.Delete
End With
End If
I really want the If statement to say something like:
If the text inside the Bookmark1 = "Entered Text Goes Here" Then do all the stuff below, else quit.
Ideas anyone?
Word 2007.
The below should work if your document is set up how I think it is, otherwise you will need to have a play around with it:
'TestTxt is the default text in the bookmark (assuming that you are not including the paragraph mark in the bookmark)
Dim TestTxt As String: TestTxt = "Enter text here"
'DMRng is the range of the the bookmark you are looking at
Dim BMRng As Range: Set BMRng = ThisDocument.Bookmarks("Bookmark1").Range
If BMRng.Text = TestTxt Then
'Start is the beginning of the bookmark - 1 (as the character before hand should be your section break?!)
BMRng.SetRange Start:=BMRng.Start - 1, End:=BMRng.End
BMRng.Delete
End If