Print specific pages from word file from excel vba - excel

I'm trying to print specific pages from a word file using Excel VBA, but I couldn't do that, I was only able to print the whole file and not the pages I wanted (changes according the value of LastPage). This is the code I used. Please help with that, thanks.
Sub PrintFile()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("D:file.docx")
objWord.Visible = False
objDoc.PrintOut from:="1", To:="LastPage".value
objWord.Quit
End Sub

Assuming you are getting an error on the line starting objDoc.PrintOut then replace that line with
objDoc.PrintOut Range:=wdPrintFromTo, From:="1", To:=CStr(LastPage)

Related

Editing The ContentControl in Word from Excel VBA

I want to edit the plain text content control in my Word application.
I searched but it seems The "plain text content control" in my target Word document does not respond to
objDoc.SelectContentControlsByTag("Name").Item(1).Range.Text
I tried with "ActiveDocument" options but I want it not to work with the active ones.
Code in VBA Excel:
Sub dataToWord()
Dim objWord As Word.Application
Dim objDoc As Word.Document
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("C:\Users\ASUS\Documents\Excell to Word - Copy\WordTesting1.docx")
objWord.Visible = True
objDoc.SelectContentControlsByTag("Name").Item(1).Range.Text = "I want to type some text here"
objDoc.Save
objDoc.Close
End Sub
I get:
Run-time error '445':
Object doesn't support this action
It refers to the line
objDoc.SelectContentControlsByTag("Name").Item(1).Range.Text = "I want to type some text here"
I have disabled the WPS app . and it worked fine.. it seems it is in conflict with the microsoft word application..

VBA find and replace in a word doc's footer

I have a document that has a bunch of <<system>> in its footers.
So far I've just been highlighting them and pasting over, which is very tedious.
I would like VBA to do this for me.
I have a macro written that takes care of all the find and replaces in the document, except it isn't working in the footers.
Looking on google, it seems that all I'm finding is how to do it with the vba in word, but I need to work from vba in excel. Is it possible to make it work from there?
vba used (works for everything in the word doc except the stuff in the footers):
Dim objword
Set objword = GetObject(, "Word.Application")
With objword.ActiveDocument.Content
With .Find
.Execute FindText:="thing to search", ReplaceWith:="thing to replace", Replace:=1 '(or 2)
End With
End With
Life is a lot easier if you add a reference to Word objects in Excel, but otherwise, this might work from Excel:
Public Sub UpdateWord()
Dim wrdObj As Object ' Application object
Dim wrdDoc As Object ' Word object
Dim sect As Object ' Section
Dim footr As Object ' Footer
Dim sel As Object ' Selection
Dim kwrd_find As String: kwrd_find = "<<system>>" ''' Keyword to find
Dim kwrd_replace As String: kwrd_replace = "Hello" ''' Word to replace keyword
Dim DocPath As String: DocPath = "C:\path\to\my\word-document.docx"
Set wrdObj = GetObject(, "Word.Application")
''' Open word document
''' Change `Visible` to False if you don't want to see it.
Set wrdDoc = wrdObj.Documents.Open(DocPath, ReadOnly:=False, Visible:=True)
On Error Resume Next
With wrdDoc
''' Run through all sections and footers (you can add headers, too).
For Each sect In .Sections
For Each footr In sect.Footers
With footr.Range.Find
.Text = kwrd_find ''' Keyword to find
.Replacement.Text = kwrd_replace ''' Word to replace keyword
.Wrap = wdFindContinue ''' Wrap it up.
Call .Execute(Replace:=wdReplaceAll)
End With
Next
Next sect
End With
''' Close and save document
Call wrdDoc.Close(SaveChanges:=True)
''' Clean up e'rything.
Set wrdDoc = Nothing
Set wrdObj = Nothing
End Sub

Macro using Documents.Open doesn't return a Document, but a String.

I want to open and read paragraphs of a Word document from an Excel macro. Here's the sample code that confuses me:
Sub example()
Dim docPath
docPath = "C:\temp\test.docx"
Dim wordApp
Set wordApp = CreateObject("Word.Application")
Dim doc
doc = wordApp.Documents.Open(docPath)
MsgBox (TypeName(doc)) 'This line displays String. According to the documentation it should be a Document.
End Sub
According to the documentation the Documents.Open method should return a Document that you can operate on. But when I check the type it says it has returned a String. Obviously I can't loop through the paragraphs of a string:
https://msdn.microsoft.com/en-us/vba/word-vba/articles/documents-open-method-word
Is the documentation wrong? Am I doing something wrong? More importantly, how do I loop through the paragraphs of a Word document from an Excel macro?
I'm using Office 365 if that matters and I have created a small Word document at C:\temp\test.docx.
try:
Set doc = wordApp.Documents.Open(docPath)
The String you are getting is some property of the Object you have created; might be the Name of the Object.................insert MsgBox doc to see what it is.
Although basically what is missing is a 'Set Doc = ...' you are guaranteed to get into trouble with a code like that. To prevent that some suggestions and a starter code (your code really, a little bit modified):
Add Word object reference from Tools\References and "type" your objects. Typing them would make it much easier to write code with intellisense support.
Never ever let the word object hang out there. Get rid of it when you are done.
Sample:
Dim docPath
docPath = "C:\temp\test.docx"
Dim wordApp As Word.Application
Set wordApp = CreateObject("Word.Application")
Dim doc As Word.Document
Set doc = wordApp.Documents.Open(docPath)
For i = 1 To doc.Paragraphs.Count
Cells(i, 1) = doc.Paragraphs(i).Range.Words.Count
Cells(i, 2) = doc.Paragraphs(i)
Next
wordApp.Quit
Set doc = Nothing
Set wordApp = Nothing

Add specific Document to specific Word.Application

May I assign the objDoc as a document of the ObjWord (after Set objDoc = oDoc.Object)?
My code looks like this:
'Declaration
Dim oDoc As OLEObject
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim WS as Worksheet
Dim strOdoc as String
'Initialization
Set WS = Whorksheets("Sheet1")
strOdoc = "WordDoc"
Set objWord = New Word.Application
'Set objWord = GetObject(, "Word.Application")
'I need using GetObject to be able to made the activated OLEDocument, invisible.
'And Need Set objWord = New Word.Application to be able
'to EndTask the WINWORD.EXE with objWord.Quit.
objWord.Visible = False
Set oDoc = WS.OLEObjects(strOdoc)
oDoc.Activate
Set objDoc = oDoc.Object
'I need here Add the objDoc to the objWord
I need objDoc to have been a document of the objWord object, which has been hidden with objWord.Visible = False (I can't use Dim objDoc As objWord.Document variable declaration).
I need the objWord to have been isolated because when using
objWord.Quit, it must not try to close other Word Documents. (Here I used Set objWord = New Word.Application)
I need using the GetObject statement to be able to made the activated OLEDocument invisible.
And Need Set objWord = New Word.Application to be able to EndTask the
WINWORD.EXE with objWord.Quit.
But how can integrate two above advantages: 1) Working Invisible with the OLEObjectDocument and 2) Perform EndTask the WINWORD.EXE if no other word documents are opened?
Please take a more logical, step-by-step approach. Bear in mind that you need the Microsoft Word Object Library to be referenced (VBE > Tools > References).
Now you can create an instance of the Word application. It is invisible by default. You can use it and quit it without affecting any other instances of the Word that might be running concurrently. That part of your code is logically correct but the recommended code is Set objWord = CreateObject("Word.Application"). This creates a new instance. I'm not sure if Set objWord = New Word.Application perhaps does the same thing but you shouldn't need both.
Now you can open a document. Use the Documents.Open method to do that. The document will be of Word.Document data type, not an OLEObject. This document will open in a window and it is that window which you can make invisible. Address it as objWord.Windows(1) or objWord.ActiveWindow. Perhaps there will be a flicker on the screen which you might combat with objWord.ScreenUpdating = False.
After these steps you would have a normal Word document, invisible in its own Window, open in an instance of Word which has no other document open in it. You can manipulate that document, close it and then quit objWord.

Insert multiple images in MS Word bookmarks via Excel

I would want images to be inserted into bookmarks in MS Word document (.docx) with the use of Excel. I stumbled upon a Word VBA workaround that is almost perfect for the job EXCEPT that it is of course, a code that sits in Word (I just save it in the global template). The reason why I would need it to be in Excel is because I can't save the macro in the .docx file --- I can't afford to save it as a macro-enabled document as it will mess up with the existing VBA in Excel (Another person made it :). I did have exhausted all effort Googling but there is no exact solution for this. For reference, here is the 'modified' code that I was talking about. I copied it from user fumei in vbaexpress.com
Sub FillABookmark(strBM As String, strText As String)
Dim j As Long
With ActiveDocument
.Bookmarks(strBM).Range _
.InlineShapes _
.AddPicture FileName:=strText
j = ActiveDocument.InlineShapes.Count
.InlineShapes(j).Select
.Bookmarks.Add strBM, Range:=Selection.Range
End With
End Sub
Sub InsertScreenshots()
Call FillABookmark("Image_1", "C:\Users\Public\Documents\Image1.png")
Call FillABookmark("Image_2", "C:\Users\Public\Documents\Image_2.png")
Call FillABookmark("Image_3", "C:\Users\Public\Documents\Image_3.png")
End Sub
I would appreciate any kind of help :)
Update:
Shoutout to Imran :) Your code has been a great help, but I can't seem to work it off to work for multiple images,.. I can't even all of the things that my attempts did, but all of them sort of pastes the new images to one and the same bookmark. Plus a failing Office 365 to add to the dilemma,. I'm reinstalling it later and will on be available for comment tomorrow :( I'm out of my wits and tried to incorporate the looping feature in the original code that I posted. The following code is my failed attempt at it:
Sub FillABookmark(bookmarkname As String, imagepath As String)
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "D:\test.docx"
Set objDoc = objWord.activedocument
With objDoc
.Bookmarks("test1").Select
.Shapes.AddPicture Filename:=imagepath
End With
With objDoc
.Bookmarks("test2").Select
.Shapes.AddPicture Filename:=imagepath
End With
With objDoc
.Bookmarks("test3").Select
.Shapes.AddPicture Filename:=imagepath
End With
End Sub
Sub InsertScreenshots()
Call FillABookmark("test1", "C:\Users\Public\Documents\image_1.png")
Call FillABookmark("test2", "C:\Users\Public\Documents\image_2.png")
Call FillABookmark("test3", "C:\Users\Public\Documents\iamge_3.png")
End Sub
If it's only the image that you want to add in a word document then use this,
Sub FillABookmark(bookmarkname As String, imagepath As String)
Dim objWord As Object
Dim objDoc As Object
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If objWord Is Nothing Then
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "D:\imran.docx"
End If
Set objDoc = objWord.activedocument
With objDoc
.Bookmarks(bookmarkname).Select
.Shapes.AddPicture Filename:=imagepath
End With
With objDoc
.Bookmarks(bookmarkname).Select
.Shapes.AddPicture Filename:=imagepath
End With
With objDoc
.Bookmarks(bookmarkname).Select
.Shapes.AddPicture Filename:=imagepath
End With
End Sub
Sub InsertScreenshots()
Call FillABookmark("test", "C:\Users\Public\Documents\1.jpg")
End Sub

Resources