Background: I currently have a document that is broken up into separate sections by section breaks in Word. I have a macro to print pdf's of the sections to a users chosen directory and a macro to export static pages as pdf's. I've entered the page numbers in the export macro for the time being because the save function works a lot faster than the print as pdf function. But I would like to have the macro export sections as pdfs with page numbers that can change.
Note: Section pages can change depending on the work I am doing on my master file, so using static page numbers in my macro is only temporary solution. Resolving this is really important for me.
What I Have So Far (This is the export macro):
Sub PLANv()
'
' PLANv Macro
'
'
Dim strName As String
strName = InputBox(Prompt:="Save To:", Title:="Save file to:", _
Default:="C:\Users\PRESTONAVH\Desktop\Task Order Files\")
If strName = vbNullString Then
Exit Sub
Else
End If
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
strName & "PLAN.pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportFromTo, From:=3, To:=4, Item:= _
wdExportDocumentContent, IncludeDocProps:=False, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
End Sub
What I Would Like to Have:
It seems that my macro that exports as a PDF does not allow me to put the sections in the range field, I've tried and it always gives me an error message. I currently have the static page range in there (3-4). I was thinking that maybe there there is some code I could enter before that, that would return the starting page number and ending page number of the section I'm exporting. Then I could assign a string to whatever is returned and then in the range function enter those strings as the page numbers?
I'm really not good at this stuff but have been going through lots of forums and trying to piece together what other people have suggested with no luck. There is probably a much easier solution, but as long as it works that would really be great. I've been trying to figure this out for some time now, but I've gone through too many forums and am a VBA super beginner.
If anyone would be able to help me out I would really appreciate it.
Thank You
Update:
I tried the export section code as recommended but my fields were erased in the exported documents and a blank page added. So I'm trying to use the section range to set the first and last integers of the export range. I can get intValue1 which gives me the last page of the section range. But I don't know how to get intValue2 for the first page of the section range. Below is what I added in between my save prompt and the export code.
Dim intValueR As Range
Dim intValue1 As Integer
Dim intValue2 As Integer
Set intValueR = ActiveDocument.Sections(3).Range
intValue1 = CStr(intValueR.Information(wdActiveEndPageNumber))
intValue2 = ??
(SOLVED)
Hi everyone, thanks for helping me out, I have the final code that is working well for me now. Here's the code:
Dim strName As String
strName = InputBox(Prompt:="Save To:", Title:="Save file to:", _
Default:="C:\Users\PRESTONAVH\Desktop\Task Order Files\")
If strName = vbNullString Then
Exit Sub
Else
End If
Dim intValue1 As Integer
Dim intValue2 As Integer
intValue1 =
ActiveDocument.Sections(1).Range.Information(wdActiveEndPageNumber) + 1
intValue2 =
ActiveDocument.Sections(2).Range.Information(wdActiveEndPageNumber)
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
strName & "PLAN.pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportFromTo, From:=intValue1,
To:=intValue2, Item:= _
wdExportDocumentContent, IncludeDocProps:=False, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
Alright so I found a solution, it's really ugly but it works. Since I didn't know how to set the first part of the section range as an integer but I did know how to set the last part of the section range as an integer. I simply set the first part as the last part of the previous section's range plus 1.
The result is this bit of code:
Dim intValueR As Range
Dim intValueR2 As Range
Dim intValue1 As Integer
Dim intValue2 As Integer
Set intValueR = ActiveDocument.Sections(3).Range
Set intValueR2 = ActiveDocument.Sections(2).Range
intValue1 = CStr(intValueR.Information(wdActiveEndPageNumber))
intValue2 = CStr(intValueR2.Information(wdActiveEndPageNumber)) + 1
If someone has a cleaner way of doing this, that would be fantastic. But if someone needs something like this, it's working for me.
Shout out to #TonyM and #jsotola!
I would suggest that you first select the section you want to export and then use wdExportSelection instead of wdExportFromTo. To select the section, see this page where Selection.Range.Sections.First.Range.Select is used, or experiment with the macro recorder. But, if you do want to use wdExportFromTo then the answer to your question about "entering those strings as page numbers" is that, yes, you have the right idea, but you would need to use integers rather than strings.
this is how to export a range ... arrived at this by recording a macro, which ended up starting with Selection.ExportAsFixedFormat .... Selection is a range object .....
ActiveDocument.Range(800, 1000).ExportAsFixedFormat _
OutputFileName:=strName & "PLAN.pdf", _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=True, _
OptimizeFor:=wdExportOptimizeForPrint, _
ExportCurrentPage:=False, _
Item:=wdExportDocumentContent, _
IncludeDocProps:=False, _
KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, _
DocStructureTags:=True, _
BitmapMissingFonts:=True, _
UseISO19005_1:=False
change first line to export 2nd section
ActiveDocument.Sections(2).Range().ExportAsFixedFormat _
you can do this to see what will be exported ... use for debugging, to see which range you are referrencing
ActiveDocument.Sections(2).Range().Select ' you can instead paste this line into the "Immediate Window", and then look at your document
Stop
Related
I have a macro that is supposed to run when I get to a specific slide. Now, the macro runs perfectly when Im in the slide editor view and not in the actual slideshow view. But when I am slideshow view the macro only runs half the code. I cannot figure it out for the life of me and any assistance would be greatly appreciated!
Private Sub NewMonthButton_Click()
Dim s As Shape
Dim Month As String
'NewMonthSelection is a text box from a user form
Month = NewMonthSelection.Text
'Delete any images on the slide
For Each s In ActivePresentation.Slides(7).Shapes
If s.Type = 13 Then s.Delete '13 is msoPicture
Next
'Add first picture
ActivePresentation.Slide(7).Shapes.AddPicture( _
FileName:="C:\Users\Public\Pictures\Sample Pictures\" & Month & "1.PNG", _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, Left:=80, Top:=120, _
Width:=550, Height:=180).Select
'This is where the code quits, it adds the first picture but not the second
'unless its in the slide editor view
ActivePresentation.Slide(7).Shapes.AddPicture( _
FileName:="C:\Users\Public\Pictures\Sample Pictures\" & Month & "2.PNG", _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, Left:=80, Top:=310, _
Width:=550, Height:=180).Select
NewMonthSelection.Text = ""
End Sub
If anyone comes across this in the future with similar code to mine, It was the select statement throwing it off. Here is my updated code to add the image:
With ActivePresentation.Slides(7).Shapes
.AddPicture _
FileName:="C:\Users\Public\Pictures\Sample Pictures\" & Month & "1.PNG", LinkToFile:=False, SaveWithDocument:=True, Left:=80, Top:=120, Width:=550, Height:=180
.AddPicture _
FileName:="C:\Users\Public\Pictures\Sample Pictures\" & Month & "2.PNG", LinkToFile:=False, SaveWithDocument:=True, Left:=80, Top:=310, Width:=550, Height:=180
End With
I want to insert files when this function is called.
I want the input file to be shown with a specific width, height, and have the icon of the file.
I also want to have the input be in a specific cell.
Is there a better way to define what cell I want the input to be in? I want the input to be in cell 'I5' but I am not sure how to go out doing this with the top and left parameters in OLEObjects.Add.
Sub FileToLink()
Dim strFileName As String
Dim strShortName As String
Dim f As OLEObject
strFileName = Application.GetOpenFileName("All Documents (*.*), *.*")
If strFileName = "False" Then
Exit Sub ' user cancelled
End If
strShortName = InputBox("What do you want to call this link?", "Short Text", strFileName)
Set f = ActiveSheet.OLEObjects.Add( _
Filename:=strFileName, _
Link:=False, _
DisplayIcon:=False, _
IconFileName:=strFileName, _
IconIndex:=0, _
IconLabel:=strShortName, _
Top:=Range("I5").Top, _
Left:=Range("I5").Left, _
Width:=10, _
Height:=10)
End Sub
Thanks to an answer I changed the Top and Left to make the input in the correct cell, however I am still unsure on how to change the width and height.I Keep getting an input box that is longer than it is tall.
I'm trying to create a macro which compares text files. However, I need a loop to compare all the files within a folder.
The macro I have now only compares between template1 and spool1 for example.
I need a loop that compares template1 with spool1.. template2 with spool2 etc. Any idea on how to do so?
I think I have to add the files into a collection first and then call it.. I'm not sure though.
Here's my codes
ChangeFileOpenDirectory "D:\Users\tmp4jj\Desktop\ComparisonTool\"
Dim template1 As Word.Document
Dim spool1 As Word.Document
Set template1 = Documents.Open("D:\Users\tmp4jj\Desktop\ComparisonTool\template1.docx")
Set spool1 = Documents.Open("D:\Users\tmp4jj\Desktop\ComparisonTool\spool1.txt")
Application.CompareDocuments OriginalDocument:=Documents("template1.docx") _
, RevisedDocument:=Documents("spool1.txt"), Destination:= _
wdCompareDestinationNew, Granularity:=wdGranularityWordLevel, _
CompareFormatting:=False, CompareCaseChanges:=True, CompareWhitespace:= _
False, CompareTables:=True, CompareHeaders:=True, CompareFootnotes:=True, _
CompareTextboxes:=True, CompareFields:=True, CompareComments:=True, _
CompareMoves:=False, RevisedAuthor:="UOB", IgnoreAllComparisonWarnings:= _
False
Thanks in advance as I'm very new to coding!
If the filenames always correspond, you can use the Dir$() function with a wildcard to find one or the other of the pair, then build the other filename out of the result. Dir$() returns the next result on subsequent calls, and then an empty String when all the files have been returned. This makes it easy to build a loop around:
ChangeFileOpenDirectory "D:\...\ComparisonTool\"
Dim template_doc As Word.Document
Dim spool_doc As Word.Document
Dim spool As String
Dim templ As String
spool = Dir$("D:\...\ComparisonTool\spool*.txt")
Do While spool <> vbNullString
templ = "template" & Left$(Left$(Right$(spool, Len(spool) - 5), _
Len(spool) - 4), Len(spool) - 9) & ".docx"
Set template_doc = Documents.Open("D:\...\ComparisonTool\" & templ)
Set spool_doc = Documents.Open("D:\...\ComparisonTool\" & spool)
Application.CompareDocuments OriginalDocument:=Documents(templ) _
, RevisedDocument:=Documents(spool), Destination:= _
wdCompareDestinationNew, Granularity:=wdGranularityWordLevel, _
CompareFormatting:=False, CompareCaseChanges:=True, _
CompareWhitespace:=False, CompareTables:=True, CompareHeaders:=True, _
CompareFootnotes:=True, CompareTextboxes:=True, CompareFields:=True, _
CompareComments:=True, CompareMoves:=False, RevisedAuthor:="UOB", _
IgnoreAllComparisonWarnings:=False
spool = Dir$
Loop
NOTE: I shortened the directory names to get rid of the side scrolling - you'll need to replace them with the actual directory path.
I've recorded a macro in word 2007 which looks like this:
Sub Makro1()
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:= _
"http://www.example.com", SubAddress:="", ScreenTip:="", TextToDisplay:= _
"text"
End Sub
In my macro, I want to set address and textToDisplay dynamically, which I tried to do by doing this simple test:
Sub Makro1()
Dim text1 As String
text1 = "joe"
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:= _
"http://www.example.com", SubAddress:="", ScreenTip:="", TextToDisplay:= _
text1
End Sub
When I ran this macro, whole Word crashed and had to recover the document, obviously I'm doing something wrong. Any help appreciated
Thanks
I was having the same problem, and found an answer on the Office Development Center
In short, the problem is in the TextToDisplay parameter. Changing your variable type from String to Variant will work around the problem.
Dim text1 As Variant
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