PDA

View Full Version : Merging two MACRO scripts (WORD)



alkhorsh
02-08-2021, 07:37 PM
I have two Macro scripts, both are working perfectly individually! But I want to marge them and have 1 script. Basically, I want to save all pages in a WORD document (like 100 pages) as PDF and name each file according to the 3rd line of each page.
The problem is they are both saving a file - one in PDF format and the other in word format...I tried to merge them but everytime something breaks in the middle..

Here are the scripts:




Sub SaveAsSeparatePDFs()

Dim strDirectory As String, strTemp As String, ipgEnd As Integer
Dim iPDFnum As Integer, i As Integer

strTemp = InputBox("How many pages is included?" & vbNewLine & "(ex: 60)")
ipgEnd = CInt(strTemp)
strDirectory = Environ("USERPROFILE") & "\Desktop"

iPDFnum = 1
For i = 1 To ipgEnd

ActiveDocument.ExportAsFixedFormat OutputFileName:= _
strDirectory & "\User--" & iPDFnum & FirstPara & ".pdf", ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
wdExportFromTo, From:=i, To:=i + 1, Item:=wdExportDocumentContent, _
IncludeDocProps:=False, KeepIRM:=False, CreateBookmarks:= _
wdExportCreateHeadingBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=False, UseISO19005_1:=False
iPDFnum = iPDFnum + 1

i = i + 1
Next i
End
End Sub

Sub RenameFile()


Dim oSection As Section
Dim r As Range
Dim TempDoc As Document
Dim FirstPara As String


Dim strDirectory As String, strTemp As String, ipgEnd As Integer
Dim iPDFnum As Integer, i As Integer


For Each oSection In ActiveDocument.Sections
Set r = oSection.Range
r.End = r.End - 1
Set TempDoc = Documents.Add
With TempDoc
.Range = r
FirstPara = r.Paragraphs(3).Range.Text
FirstPara = Left(FirstPara, Len(FirstPara) - 1)
.SaveAs FileName:=FirstPara & ".doc"
.Close
End With
Set r = Nothing
Set TempDoc = Nothing
Next
End Sub

gmayor
02-08-2021, 09:41 PM
This looks as though you are trying to split the output of a mail merge to documents and pdf files. Rather than re-invent the wheel - see  https://www.gmayor.com/MergeAndSplit.htm. This will either split the existing merged document as required, using a selected paragraph from the section to name the sections (with appropriate correction for illegal filenames and duplicates) or better still it can split the merge on the fly similarly, named from the data.

macropod
02-08-2021, 09:53 PM
Cross-posted at: https://stackoverflow.com/questions/66112156/merging-two-macro-scripts-word
Please read VBA Express' policy on Cross-Posting in Rule 3: http://www.vbaexpress.com/forum/faq.php?faq=new_faq_item#faq_new_faq_item3