VBA - Documents.Activate function does not work properly - vba

I'm not very used to VBA language, so I come to you for help to solve my problem.
Basically, what I want to do is, while having a MS Word 2010 document opened, open a new one, set the focus on it and do stuff with it.
The problem I'm facing is that I can effectively open the new document, but the .activate function to set the function on it doesn't work, as the instructions following it are still executed in the first document.
Here is my code:
Private Sub BOK_Click()
*...instructions...*
'Opens a new document
Application.Documents.Add
'Select the latest opened document and sets the focus on it
Application.Documents(Application.Documents.Count).Activate
* do stuff *
End Sub
If it may help, the full context is :
I have a main template with 6 pre-filled templates in it, and following the choice of the user (from a drop-down form) it selects the right pre-filled template and opens it in a new Word document, then closed the main template.

What Documents.Add does:
Create a window
Render a copy of the provided (or Normal, in this case) template
Display it in the window
Raise the index of all open documents by 1
Assign index 1 to the newly added document
Bring the window to the front and give focus to it
There's (usually) no need to explicitly activate a document you just added. If you must or want to use Activate, it's best practice to reference a document by it's name, since indexes tend to drift (as described above).
doc1 = ActiveDocument.Name
Documents.Add
doc2 = ActiveDocument.Name
' Do something with document2
Documents(doc1).Activate
' Do something with document1
Documents(doc2).Activate
' Do something with document2 again

Related

How to open and edit read-only word doc through VBA

I have a macro which should open, edit and copy the contents of read-only documents into a new document, then closes the original ones without saving. On my computer I get a runtime error 6124: "You are not allowed to edit this selection because it is protected."
When I open the document through VBA it says I am restricted with view only, however when I open it manually I get the notification that the author would like me to open it read only, and I can refuse.
The weird thing is I sent the macro to my colleague to test it, and the same code on the same files can do the editing for them.
Is there a setting I am not aware of that allows this to happen?
Is there a way to get VBA to open the read-only document with editing access?
I have tried to change the document attribute through runtime script, but it did not work:
Dim fso, doc As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set doc = fso.GetFile("path")
doc.Attributes = 0
Documents.Open("path")
End Sub

Can I apply and execute a code from a different document?

Is there a way to have two documents where the first document has all the code and functions that will execute and apply on the second document?
For example: Doc 1 has a button and all of the code, and when I press that button, it will draw shapes on doc 2.
I was wondering if DocumentOpened is the fitting method. Any help or tip would be appreciated. Thank you!
PS. My other question was closed so I had to make a new one...
As with any Office product, you can use the open application object to reference the document collection for that application.
Also, when you execute the Documents.Open function (or .Add function for new files) it will return a valid Document object. You then use that object to perform other operations.
Visio Documents.Open Method Documentation
' open existing document
Dim viDoc as Object
Set viDoc = Documents.Open(sFilename)
or
' create new document
Dim viDoc as Object
Set viDoc = Documents.Add(sFilename)

Executing mailmerge removes all bookmarks. What's the alternative?

So my challange is this.
I've created a Word Macro Enabled Template (MS Word 2016) which creates a document using the MailMerge function using data from an Excel file which colleagues complete.
Once completed, they add in their signature - a scanned jpeg file of their signature from a central network.
My code worked on the principle of attaching to a bookmark, unbeknown to me that when executing a MailMerge, it removes all bookmarks.
I am thinking that if I can change my code after ActiveDocument so that instead of looking for Bookmark it looks for specific text, I can then insert this text in the specific place in the Word template so when the MailMerge is executed it places their signature in that specific [text] place.
Is this possible?
Thanks in advance.
My code is
Sub CurrentUserSignature()
Dim folder As String
folder = "C:\\MacroTemp\\"
Dim path As String
path = folder & Application.UserName & ".jpg"
Dim shape As InlineShape
Set shape = ActiveDocument.Bookmarks("Signature").Range.InlineShapes.AddPicture(path, False, True)
With shape
.LockAspectRatio = msoTrue
.Height = CentimetersToPoints(4.3)
End With
End Sub
`
You could simply insert a borderless single-cell table, a Rich Text Content Control, or a Picture Content Control at the desired location in the mailmerge main document, then access each of those in the output document. If you use a borderless single-cell table, you can give it a fixed height and width so the inserted image's size is automatically constrained to fit.
Where multiple output documents are being produced, each to be signed by the same person, you might do better to insert the signature into the mailmerge main document before execution, then close that without saving changes post-merge.
Alternatively, especially if different records require different signatures and the relevant details can be gleaned from the data source, you can add field coding to the mailmerge main document to automatically add the signature images. See Managing Mailmerge Graphics in the Mailmerge Tips and Tricks thread at:
http://www.msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html
or:
http://windowssecrets.com/forums/showthread.php/163017-Word-Mailmerge-Tips-amp-Tricks

Batch add a macro to word documents?

I have several hundred .doc word documents to which I need to add a macro which runs when the .doc file is opened and creates a header for said document based on the file name. Is there a way to do this as a batch? I have been individually opening each document and going into visual basic --> Project --> This Document then inserting a .txt file which contains the code. Is there a fast way to do this for multiple documents?
As a learning exercise, put this into the "ThisDocument" part of Normal (the Normal.dot template) in the VBE
Open a word document and watch what happens.
I don't think you need to put your code in every single file, I think you should be OK with using the Document_Open event in Normal.dot.
Just make sure it shows up as a reference in your word documents that you open but I don't see why it wouldn't
If you absolutely need it in every file then it can be done but the problem is if you make one small change to the code, you have to go through all this again. The idea with code is to write it once, use it many times.
You can write VBA code that alters the VBA code in other documents, but you need to "Trust access to the VBA project object model" in the Trust Centre options. This could open you up to viral code if you download Word documents with malicious VBA code in them. What you want to do, essentially, is write a VBA virus. There are legitimate reasons for doing this, and also malicious ones, I leave the ethics of the uses of these techniques up to the user. Knowledge itself is not malicious.
Here's the meat, you will need to write your own code to loop through the documents and possibly save them as .docm files.
Sub ReplaceCode()
Set oDoc = ActiveDocument
Set oComponents = oDoc.VBProject.VBComponents
For i = oComponents.Count To 1 Step -1
If oComponents(i).Type = 100 And oComponents(i).Name = "ThisDocument" Then
With oComponents(i).CodeModule
.DeleteLines 1, .CountOfLines
.AddFromFile "C:\ThisDocument.cls"
End With
End If
Next i
End Sub
Also, if you create your code file by exporting from VBA, you will need to remove this from the top of the .cls file:
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Personally, I would drive this from Excel, maybe using a worksheet to hold a list of the files or locations to update, and another sheet for the code to populate with a list of files updated.

Word macros not running correctly when opened from PowerPoint action button

I have a Word template (suggestion from) which includes an autonew macro to insert a reference number at a book mark and an action button (Submit)which saves the resulting document with the reference number as part of the file name and closes Word. This works perfectly well when opening the template via Windows Explorer.
We also have a PowerPoint show with action settings hyperlinking to various documents. The link will open the above template OK but does not insert the reference number. Also when the 'submit' button is hit, the file saves as another template with the reference number included.
I am not sure if the issue is Word or PowerPoint-related. The code for the Word template is
Sub AutoNew()
REF = System.PrivateProfileString("L:\Local\Lab\Section - Support Services\Health and Safety\H&S Suggestions\Settings.Txt", _
"MacroSettings", "REF")
If REF = "" Then
REF = 1
Else
REF = REF + 1
End If
System.PrivateProfileString("L:\Local\Lab\Section - Support Services\Health and Safety\H&S Suggestions\Settings.Txt", "MacroSettings", _
"REF") = REF
ActiveDocument.Bookmarks("REF").Range.InsertBefore Format(REF, "000#")
End Sub
Private Sub CommandButton1_Click()
REF = System.PrivateProfileString("L:\Local\Lab\Section - Support Services\Health and Safety\H&S Suggestions\Settings.Txt", _
"MacroSettings", "REF")
ActiveDocument.SaveAs FileName:="L:\Local\Lab\Section - Support Services\Health and Safety\H&S Suggestions\Suggestion " & Format(REF, "000#.doc")
Application.Quit
End Sub
Any help or pointers would be appreciated as if it works I'd like to use for various other templates.
From the description, it's kind of hard to get an accurate idea of what's happening, but it SOUNDS like the the AUTONEW just might not get run in that particular combination.
You could verify this by using some logging or MSGBOX calls to see exactly what macros are being run, when.
Check the docs on Autonew here
http://support.microsoft.com/kb/211659
Sounds like it won't run if the macro is saved in Normal, which doesn't sound like the case here but it's worth noting.
You might also consider using the AutoOpen macro and checking other elements to make sure this is a brand new doc instead of one that's already been saved (like checking the content of the Document.Fullname property).