In my document I have the Format Page Numbers / Start at: set to 0 so that the title page is not counted.
When I do a SaveAs via VBA the document loses that setting! It was also losing the Different First Page setting so I set that directly in VBA which fixed that problem. I think that because I am formatting the footer via VBA before I do the SaveAs I am somehow affecting the settings? Anyway, I tried setting the Start At page number after the SaveAs but it doesnt set it.
' Save our new Workbook - the output file
' That makes the new file the ActiveDocument
ActiveDocument.SaveAs filename:=fname & ".docx", FileFormat:= _
wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False
' Sets this option correctly
ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = True
' Problem: Doesnt set this option
ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).PageNumbers.StartingNumber = 0
' Update the TOC
ActiveDocument.TablesOfContents(1).Update
Any ideas?
Thanks,
Murray
"The RestartNumberingAtSection property, if set to False, will override the StartingNumber property so that page numbering can continue from the previous section." (http://msdn.microsoft.com/en-us/library/office/ff821408.aspx)
Therefore, you have to set the RestartNumberingAtSection property to true:
With ActiveDocument.Sections(1)
.Footers(wdHeaderFooterPrimary).PageNumbers.RestartNumberingAtSection = True
.Footers(wdHeaderFooterPrimary).PageNumbers.StartingNumber = 0
End With
Regards,
Leo
Related
I am working on a Word macro to print a letter and its envelope to two different printers:
Sub PrintEnvelopeAndLetter()
'
' PrintEnvelopeAndLetter Macro
'
'
Dim sCurrentPrinter As String
Dim pageCount As Integer
Dim currentPosition As Range
Set currentPosition = Selection.Range 'Save the current cursor position
pageCount = ActiveDocument.ActiveWindow.Panes(1).Pages.Count
' Prompt the user to ask if they are sure they are ready to print
Result = MsgBox("Are you sure you are ready to print?" & vbCr & vbCr & "Read through your letter one last time.", _
vbYesNo + vbDefaultButton2 + vbApplicationModal + vbExclamation)
If Result = vbNo Then
Exit Sub
End If
' Display a message box asking if the user has entered the correct date
' at the top of their letter.
Result = MsgBox("Did you enter the correct date at the top of your letter?", _
vbYesNo + vbDefaultButton2 + vbApplicationModal + vbExclamation)
If Result = vbNo Then
Exit Sub
End If
' Launch the Spelling and Grammar Check
ActiveDocument.CheckSpelling
ActiveDocument.CheckGrammar
' Save the document to the disk and do not prompt the user
' to save it if the user has made changes
If ActiveDocument.Saved = False Then
ActiveDocument.Save True
End If
' Get the total number of pages in the document. NOTE: The
' envelope counts as a page
sCurrentPrinter = ActivePrinter 'Save the current printer
ActivePrinter = "HP ENVY Photo 7800 series"
Selection.HomeKey Unit:=wdStory ' move to the top of the document (envelope)
Application.PrintOut FileName:="", Range:=wdPrintCurrentPage, Item:= _
wdPrintDocumentWithMarkup, Copies:=1, Pages:="", PageType:= _
wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
PrintZoomPaperHeight:=0
ActivePrinter = "HP OfficeJet Pro 8030 series"
For J = pageCount To 2 Step -1
Selection.GoTo wdGoToPage, wdGoToAbsolute, J
Application.PrintOut FileName:="", Range:=wdPrintCurrentPage, Item:= _
wdPrintDocumentWithMarkup, Copies:=1, Pages:="", PageType:= _
wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
PrintZoomPaperHeight:=0
Next
ActivePrinter = sCurrentPrinter 'Restore the original printer
' Scroll the insertion point to the very beginning of the document
Selection.HomeKey Unit:=wdStory
' Save the document to the disk and do not prompt the user
' to save it if the user has made changes
If ActiveDocument.Saved = False Then
ActiveDocument.Save NoPrompt:=True
End If
End Sub
I think that my code is correct, but I was hoping if I could get a second pair of eyes. It seems to be indicating that the invalid line is:
ActiveDocument.Save NoPrompt:=True
But I think that it is correct -- see the following link:
https://learn.microsoft.com/en-us/office/vba/api/word.document.save
Consulted the link:
https://learn.microsoft.com/en-us/office/vba/api/word.document.save
I checked my own VBA code and it seems as if I am specifying the NoPrompt property correctly.
I am using Microsoft® Word for Microsoft 365 MSO (Version 2210 Build 16.0.15726.20188) 64-bit on Windows 10. I did not change my code (at least, I do not think so). The macro worked perfectly the day before yesterday.
I have also checked my printers, and both of the printers listed in the macro are installed:
Figure 1. A screenshot of my installed Printers and Scanners.
I am not entirely sure what else to check.
FIRST UPDATE
I commented out both occurrences of the code
' Save the document to the disk and do not prompt the user
' to save it if the user has made changes
If ActiveDocument.Saved = False Then
ActiveDocument.Save NoPrompt:=True
End If
in the macro, and the macro works, so I know for certain that this is the code that it is complaining about. It would seem that the compiler is complaining about a syntax error somewhere, or a function parameter that is not valid. However, every source I've consulted seems to point to this as being valid code, so I am stumped.
I'd really appreciate it if someone could help me out.
Am I doing something wrong?
I have an MS Word document with macros (.docm)
Based on many StackOverflow posts, I've written a macro to export as a pdf and save as a .docx
I open/edit the .docm document, that has an onSave macro that saves the document in .pdf format and .docx format which I distribute for other people to use. I will always be making my changes to the .docm document.
My issue is that doing so converts the active(open) document from .docm to .docx such that I'm no longer making my changes to the .docm.
Sub SaveActiveDocumentAsDocx()
On Error GoTo Errhandler
If InStrRev(ActiveDocument.FullName, ".") <> 0 Then
Dim strPath As String
strPath = Left(ActiveDocument.FullName, InStrRev(ActiveDocument.FullName, ".") - 1) & ".docx"
ActiveDocument.SaveAs2 FileName:=strPath, FileFormat:=wdFormatDocumentDefault
End If
On Error GoTo 0
Exit Sub
Errhandler:
MsgBox "There was an error saving a copy of this document as DOCX. " & _
"Ensure that the DOCX is not open for viewing and that the destination path is writable. Error code: " & Err
End Sub
I can find no parameter to prevent this conversion of the active document in either "saveas" or "saveas2"
Furthermore, after the "saveas" command, any additional lines in the original macro are not executed because the active document no longer contains macros. I tried adding lines to the macro to reopen the original .docm and then close the .docx but those commends never execute.
I'm hoping I'm just missing something simple?
Sub SaveAMacrolessCopyOfActiveDocument()
' Charles Kenyon 2 October 2020
' Save a copy of active document as a macrofree document
'
Dim oDocument As Document
Dim oNewDocument As Document
Dim iLength As Long
Dim strName As String
Set oDocument = ActiveDocument ' - saves a copy of the active document
' Set oDocument = ThisDocument '- saves copy of code container rather than ActiveDocument
Let iLength = Len(oDocument.Name) - 5
Let strName = Left(oDocument.Name, iLength)
Set oNewDocument = Documents.Add(Template:=oDocument.FullName, DocumentType:=wdNewBlankDocument, Visible:=False)
oNewDocument.SaveAs2 FileName:=strName & ".docx", FileFormat:= _
wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False, CompatibilityMode:=15
oNewDocument.Close SaveChanges:=False
' Clean up
Set oDocument = Nothing
Set oNewDocument = Nothing
End Sub
The above code creates and saves a copy of the ActiveDocument with the same name but as a .docx formatted document (macro-free). The visible property in the .Add command means that it will not appear on screen and it is closed by the procedure. The new document will appear in Recent documents.
I am trying to use VBA in an open .docm file to open a 2nd read only .docx file and then insert -> object -> text from file (a 3rd read only .docx stored within the same folder).
The below code correctly opens and merges the two files but when it comes to saving the output it returns a Run-Time 13 “mismatch” error. My limited understanding leads me to believe that at the point where I am saving, the active document reference is still the original .docm and it is the .docx designation that then causes the conflict.
I am really struggling to manage the active document reference to avoid this. Presumably I am missing something very simple, all assistance is very gratefully received.
Documents.Open ActiveDocument.Path & "\DocA.docx", Visible:=True
Selection.InsertFile FileName:=ActiveDocument.Path & "\DocB.docx", Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False
ActiveDocument.SaveAs2 "C:\Users\" & Environ("UserName") & "\DocC" & ".docx", FileFormat:= _
wdFormatXMLDocument
ActiveWindow.Close
Putting flesh on John Korchok's comment:
Sub deleteme3()
Dim oldDoc As Document
Set oldDoc = Documents.Open(ActiveDocument.Path & "\DocA.docx", Visible:=True)
oldDoc.Activate
selection.Collapse Direction:=wdCollapseEnd 'to insert at end of document
selection.Range.InsertBreak Type:=wdPageBreak
Selection.EndKey Unit:=wdStory
Selection.InsertFile FileName:=ActiveDocument.Path & "\DocB.docx", range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False
oldDoc.SaveAs2 "C:\Users\" & Environ("UserName") & "\DocC" & ".docx", FileFormat:= _
wdFormatXMLDocument
oldDoc.Close
Set oldDoc = Nothing
End Sub
Note this puts the inserted document at the end of the original document. You may want to use a next-page section break instead if there is header/footer differentiation. If you need that, please comment and I will include it.
There are a number of break types. Here is the enumeration of all of them if you are interested. The following types create a page break of one sort or another:
wdPageBreak (the default)
wdSectionBreakNextPage
wdSectionBreakOddPage (starts section on next odd-numbered page - good for chapters)
wdSectionBreakEvenPage (starts section on next even-numbered page - rarely used)
If wanting to preserve headers and footers additional code would be needed.
(Every section in a Word document has three headers and three footers, even if they are not displayed or used.)
' Break Link to Previous in newly added section for all of the headers and footers
Dim oHeaderFooter As HeaderFooter
Dim iCounter As Long
Let iCounter = ActiveDocument.Sections.Count
' break link in headers
For Each oHeaderFooter In ActiveDocument.Sections(iCounter).Headers
Let oHeaderFooter.LinkToPrevious = False
Next oHeaderFooter
' repeat for footers
For Each oHeaderFooter In ActiveDocument.Sections(iCounter).Footers
Let oHeaderFooter.LinkToPrevious = False
Next oHeaderFooter
Active Document is called “FinalDocument”
The following is in a loop (ie. Report1, Report2, etc..)
DoCmd.OpenReport ReportName, acPreview, , "Report1”
DoCmd.OutputTo acOutputReport, ReportName, acFormatRTF, “WordDoc1”
ActiveDocument.Content.InsertFile FileName:=WordDoc1, Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False
I am successfully getting text from Report1 to FinalDocument.
My problem is that on every pass throught loop, InsertFile is REPLACING text.
I want to APPEND Text from Report1 to FinalDocument thereby building FinalDocument one pass at a time.
You should work with a Range object so that you can target the insertion point. First, set theRange to the entire document, then "collapse" it to a point - think of it like pressing the right-arrow key to make a selection a blinking cursor at the end of the selection.
For example:
Dim rng as Word.Range
Set rng = ActiveDocument.Content
rng.Collapse Word.WdCollapseDirection.wdCollapseEnd. 'Or use 0
rng.InsertFile FileName:=WordDoc1, Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False
Try this:
ActiveDocument.ActiveWindow.Selection.InsertFile FileName:=WordDoc1, Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False
i am using this code to PrintOut a document three times in vba:
...
Application.PrintOut fileName:="", Range:=wdPrintAllDocument, Item:= _
wdPrintDocumentContent, Copies:=1, Pages:="", PageType:=wdPrintAllPages, _
ManualDuplexPrint:=False, Collate:=True, Background:=True, PrintToFile:= _
False, PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
PrintZoomPaperHeight:=0
...
sometimes if i run this line of code, it will stopp working. Word freeze and nothing happend. I can only stop the process. i checked the PrinterSettings by
MsgBox Application.ActivePrinter
The activeprinter exists and is ready. What else can be the problem?
I am using word 2007.
Thanks for hints
Try using Document.PrintOut because Application.PrintOut prints active document, so if you're simultaneously working with another word document you can send to printer your document instead of desired one.