How to stop a Word Document immediately when newly created - vb.net

I have a VS2010 Vb.net program that creates a Word 2007 file.
My Normal.dot file is customised to give me a new Tab with Buttons in that do specific things via VBA in the Normal.dot program when those Buttons are pressed.
This all works fine, however, I now want to add some functionality whereas as soon as the new Word document is created, it edits a Task in Outlook.
I have edited the 2 "This Document" Procedures and you can see my Normal.Dot file in the attached Screenshot.
When I run my VB.Net program to create a brand new Word 2007 document, the program does NOT stop on either of the message boxes, it just continues and opens the Word document as before, my code is below, what am I doing wrong ?!?
'Open or Create Word document for Editing
myNewsLetter = myFolder + myLeague + "News" + mySession + ".doc"
If File.Exists(myNewsLetter) Then
'do nothing
Else
myTemplate = myTempFolder + "NL Skeleton.doc"
File.Copy(myTemplate, myNewsLetter)
Create_Blank_Newsletter()
End If
'Open Word Newsletter, or switch to it if it's already open
Dim myFileOpen As Boolean
myFileOpen = IsFileOpen(myNewsLetter)
If myFileOpen = False Then
MSDoc = MSWord.Documents.Open(myNewsLetter)
End If
MSWord.WindowState = Word.WdWindowState.wdWindowStateNormal
MSWord.Visible = True
MSWord.ActiveDocument.Bookmarks("\StartOfDoc").Select()

OK, sorted this, the full discussion can be found here ... http://www.vbaexpress.com/forum/showthread.php?p=286771#post286771
Basically, I'm not creating a NEW document, I am creating a new document via a Copy and then opening that existing document !!!

Related

MS Word runs on background and requests documents to be saved even though it is already saved

I have a procedure that creates a PDF file according to an ms word template and its data is retrieved from a database.
It works fine, creates a PDF file perfectly , no run time errors. The problem is that whenever I shut off the computer, ms word prevents the shutdown and if I press cancel ms word shows a message;
The code goes like this;
Dim wordApp As Word.Application
Dim templateBookmarks As Word.Bookmarks
Dim templateName As String
Dim template As Word.Document
'Some other variables for computations
wordApp = CreateObject("Word.Application")
sourceTable = New DataTable
'Some other procs to fill the data table
templateName = "Foo Template.docx"
template = wordApp.Documents.Add(templatePath & templateName)
templateBookmarks = template.Bookmarks
templateBookmarks.Item("sample bookmark").Range.Text = "foo"
'Then fills the table in the template like...
template.Tables(1).Cell(1, 1).Range.Text = dataSource.Rows(0).Item(0)
'Then saves the document as a pdf
Dim saveName As String = "sample file"
template.SaveAs2(savePath & saveName, Word.WdSaveFormat.wdFormatPDF)
I have tried to force garbage collection for the word COM resources, as well as changing the template from an actual document i.e. docx to a word template .dotx. I also tried the method Quit() but it only shows the ms word message much earlier. This is the first time I needed to use interop so pardon if I don't have much idea about it.
The files I needed are saved, the only problem is the ms word message and unsaved and unnecessary files e.g. Document1,Document2,Document3 that seems to be created aside from the required PDF
Use the Document.Close method which closes the specified document after saving files using the PDF file format. It allows specifying the SaveChanges parameter which specifies the save action for the document. Can be one of the following WdSaveOptions constants: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges.
On Error GoTo errorHandler
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
errorHandler:
If Err = 4198 Then MsgBox "Document was not closed"

CommandBars("Text").Controls not deleted when exiting the document - VBA word add-in

I'm trying to create a add in for MS Word with VBA.
It has a "AutoExec" procedure that creates a new item in the CommandBar("Text") collection (right click menu) and a "AutoExit" that deletes this created item.
As an example, I tried the code below that create an item "How Many Pages?", which executes a macro displaying the number of pages in the active document.
This is the AutoExec Code:
Public Sub AutoExec()
Dim objcommandbutton As CommandBarButton
Call MsgBox("AutoExec")
Set objcommandbutton = Application.CommandBars("Text").Controls.Add _
(Type:=msoControlButton, Before:=1)
objcommandbutton.Caption = "How Many Pages?"
objcommandbutton.OnAction = "HowManyPages"
End Sub
This is the AutoExit Code:
Public Sub AutoExit()
Dim objcommandbutton As CommandBarControl
Call MsgBox("AutoExit")
For Each objcommandbutton In Application.CommandBars("Text").Controls
If objcommandbutton.Caption = "How Many Pages?" Then
objcommandbutton.Delete
End If
Next objcommandbutton
End Sub
This is the Main Macro Code:
Public Sub HowManyPages()
If Documents.Count > 0 Then
Call MsgBox(ActiveDocument.BuiltInDocumentProperties("Number of Pages"))
Else
Call MsgBox("No document is currently active.")
End If
End Sub
When exiting the document, the Button previously added in CommandBars("Text") collection is not deleted. I see this when I open a new blank Word document and the button remains in the right click menu.
I know that the routine is performed correctly because there is a MsgBox instruction to verify it.
This only happen with the AutoExit subroutine of a add-in, that is, loaded as a add-in: running the code in a macro with vba module works fine.
Any help?
When working with the CommandBars object model in Word it's necessary to always specify the Application.CustomizationContext.
Word can save keyboard layouts and CommandBar customizations in various places: the Normal.dotm template, the current template or the current document. The default when you create a CommandBar addition may not be the3 same as the default when trying to delete something.
Since this is an add-in, I assume you want the change for the entire Word environment (any open document). In that case, use the context NormalTemplate. Use this before any calls to CommandBar:
Application.CustomizationContext = NormalTemplate
Note: for saving a customization in the current document: = ActiveDocument; for saving in the template attached to the current document: = ActiveDocument.AttachedTemplate.
I solved my problem with a workaround:
I was trying to "add" a template (.dotm) as a add-in (in the "Templates and Add-ins" window) to use my VBA project in a new document. That's why I was using the AutoExec() and AutoExit() procedures.
But only now I figure out that just "attaching" the .dotm template to the active document (in the same "Templates and Add-ins" window, as show in the figure below) makes the functions Private Sub Document_Open() and Private Sub Document_Close() to run normally. Which solves my problem.
Even so, I think there is a certain "issue" with the AutoExit() procedure when trying to change the CommandBars itens. But that's ok for now.
enter image description here

word vba: documents.add: put this new document on top

I am using VBA for MS Word. I created a macrofile (docm) to create a new word-document using documents.add....
I want to switch from my macro-document to my new created document on the screen:
Sub test()
Dim MacroDocument As Document
Set MacroDocument = ActiveDocument
Dim newDocument As Document
Set newDocument = Documents.Add
'try to show my macroDocument on the windows screen,
MacroDocument.Select
stop
' now to the new document
newDocument.Select
End Sub
Why doesn't it work?
Any ideas?
document.Select just selects the document but doesn't displays it.
Use MacroDocument.Activate and newDocumente.Activate instead.
When you add a document, the new document automatically becomes the active one and will replace the current one on your screen. Therefore, in most cases the task isn't to make it show but to keep the previous one on top. In such a case making the new document invisible is one of the options you might want to consider.
Set NewDocument = Documents.Add(Visible:=False)

Cannot find bookmarks from OpenXML appended document

using the following code snippet I open a document template (DOTX) and then append another document. Both have bookmarks.
Dim m_word As WordprocessingDocument = = WordprocessingDocument.Open("FrontPage.dotx", True)
Dim altChunkId As String = "ChunkId1"
Dim mainPart As MainDocumentPart = m_word.MainDocumentPart
Dim chunk As AlternativeFormatImportPart = mainPart.AddAlternativeFormatImportPart(
DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId)
Using fileStream As IO.FileStream = IO.File.Open("Appendix.dotx", IO.FileMode.Open)
chunk.FeedData(fileStream)
End Using
Dim altChunk As AltChunk = New DocumentFormat.OpenXml.Wordprocessing.AltChunk()
altChunk.Id = altChunkId
mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph).Last())
mainPart.Document.Save()
Now if I try to loop trough all bookmarks like this:
Dim docbody As Body = doc.GetFirstChild(Of Body)()
For Each bookmarkStart As BookmarkStart In docbody.Descendants(Of BookmarkStart)()
' Do something with the bookmarks
Next
I only get the bookmarks of the original frontpage.dotx, none of the bookmarks of the appendix.dotx is found.
If I save the document to a file, all the bookmarks are there when I open it using Word. I can also reopen the saved file i C# and then all bookmarks can be found using the above For Each loop. The question is, how can I get all the bookmarks after appending without saving and reloading the document?
When you use AltChunk to embed a document the entire file is embedded into the document - it's NOT integrated. That only happens when the combined document is opened by Word. If you need to work through all the bookmarks you need to either
Open each document, do the bookmarks, and THEN combine the two using AltChunk OR
Not use AltChunk to combine the documents, and transfer the second document part-by-part into the first document.

Manipulate visio shapes with data passed from vb.net

I have the below code which is opening visio, opening a file in visio, printing the file and then closing; this all works fine.
However, now my task is to pass information over to the visio document page called 'Ticket Task', bind that information to some shapes and then print it.
I know this is possible with vb6 (that is what the outdated code is written in), however is there a way to do this in vb.net?
Thanks!
Code:
''Set up the file path
Dim docPath As String = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\" + splFileData(0) + "\" + splFileData(1) + ".vsd"
'Set up the attributes for the opening/printing of the document.
psi.UseShellExecute = True
psi.Verb = "print"
'psi.EnvironmentVariables.Add("Orders", "Hello")
psi.Arguments = printer
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = docPath
Console.WriteLine("Printing: " + docPath)
'Start the process (open visio document, print, close)
Process.Start(psi)
You'll have to change the way you're opening and printing Visio documents. This tutorial shows how to use VB.NET to work with documents. The Open function returns an object of type Microsoft.Office.Interop.Visio.Document. You can use this object to attach information to shapes as discussed in here. In fact, the VB.NET code is very similar to VB6. If you want Visio to be invisible, you can open the document as follows:
Microsoft.Office.Interop.Visio.InvisibleApp application = new Microsoft.Office.Interop.Visio.InvisibleApp();
application.Visible = false;
Microsoft.Office.Interop.Visio.Document doc = application.Documents.Open...