Advertisement
duck__boy1981

Export document

Jan 19th, 2015
1,398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Option Explicit
  2.  
  3. Sub BeginExportDocument()
  4.     frmChooseDocument.Show
  5. End Sub
  6.  
  7. '**
  8. ' Get value of every instance of 'Heading 1' formatted text within the document
  9. '
  10. ' @param Boolean allowMultiple     Whether or not to allow multiple instances of each 'Heading 1'
  11. ' @retrun Array(String) headings   All 'Heading 1' instances that have been found
  12. '*
  13. Function GetHeadings(Optional ByVal allowMultiple As Boolean = False) As String()
  14.  
  15.     Dim blnFound As Boolean     ' Whether or not a 'Heading 1' style has been found
  16.    Dim headings() As String    ' The 'headings' in this documents
  17.    Dim i As Integer            ' Dummy counter for expanding the 'headings' array as necessary
  18.    Dim sanitizedText As String ' The sanitized 'Heading 1' text to add to the 'headings' array
  19.    
  20.     '** Get the current location of the cursor in the document so that the cursor can be returned there after the 'headings' have been found *'
  21.    Dim currentPosition As Range
  22.     Set currentPosition = Selection.Range
  23.    
  24.     '** Initilise the 'headings' array to avoid errors '*
  25.    i = 0
  26.     ReDim headings(i)
  27.     headings(i) = ""
  28.    
  29.     '** Set up the Find conditions for the Find *'
  30.    Selection.HomeKey Unit:=wdStory
  31.     Selection.Find.ClearFormatting
  32.     Selection.Find.Style = ActiveDocument.Styles("Heading 1")
  33.     With Selection.Find
  34.         .Text = ""
  35.         .Replacement.Text = ""
  36.         .Forward = True
  37.         .Wrap = wdFindContinue
  38.         .Format = True
  39.         .MatchCase = False
  40.         .MatchWholeWord = False
  41.         .MatchWildcards = False
  42.         .MatchSoundsLike = False
  43.         .MatchAllWordForms = False
  44.     End With
  45.    
  46.     '** Execute the Find and repeat until there are no more matches *'
  47.    blnFound = True
  48.     While blnFound
  49.        
  50.         With Selection.Find
  51.             .Execute
  52.            
  53.             '** Check to see if a match has been found... *'
  54.            If .Found = True Then   ' There is a match
  55.            
  56.                 '** Clean the text to ensure that there is no unnecessary whitespace *'
  57.                sanitizedText = Left(Selection.Text, Len(Selection.Text) - 1)
  58.                
  59.                 '** Ensure that the match does not already exist in the 'headings' array (if multiple entries are not allowed) *'
  60.                If _
  61.                 (Not allowMultiple And Not InArray(sanitizedText, headings)) Or _
  62.                 allowMultiple _
  63.                 Then
  64.                     ReDim Preserve headings(i)
  65.                     headings(i) = sanitizedText
  66.                     i = i + 1
  67.                 End If
  68.                
  69.                 '** Move to the right of the selection to ensure it is not matched in the next execution of this Find *'
  70.                Selection.MoveRight Unit:=wdCharacter, Count:=1
  71.                
  72.             Else    ' No match
  73.                blnFound = False
  74.             End If
  75.            
  76.         End With
  77.        
  78.     Wend
  79.    
  80.     '** Return the cursor to it's original position *'
  81.    currentPosition.Select
  82.    
  83.     '** Return the headings that have been found *'
  84.    GetHeadings = headings
  85.    
  86. End Function
  87.  
  88. '**
  89. ' Handle the selection of a chosen 'Heading 1' section (and it's contents) and it's export to another document
  90. '
  91. ' @param required String headingName   The name of the 'Heading 1' section to select
  92. ' @raturn Boolean result               Whether or not the export process as a whole was successful
  93. '*
  94. Function StartExportDocument(Optional ByVal headingName As String = "") As Integer
  95.    
  96.     '** Ensure that a 'headingName' has been passed *'
  97.    If headingName = "" Then Exit Function
  98.    
  99.     '** Set the result to '0' initially *'
  100.    Dim result As Integer
  101.     result = 0              ' Not successful, but don't display any error
  102.    
  103.     '** Move the cursor to the start of the document to ensure that the whole of the desired document is selected *'
  104.    Selection.HomeKey Unit:=wdStory
  105.    
  106.     '** Select the 'Header 1' formatted text of the 'headingName' that has been passed and the content under it and check whether or not the selection is valid *'
  107.    If Functions.SelectSection(headingName) Then  ' It is valid
  108.        If Functions.CopyToNewDocument(headingName) Then
  109.             result = 1  ' Successful
  110.        Else
  111.             result = 2  ' Not successful
  112.        End If
  113.     Else ' It is not valid
  114.    
  115.         '** Warn the user that an error has occured *'
  116.        Call MsgBox("Sorry, the heading """ & headingName & """ could not be found, so there is nothing selected to export." & vbCrLf & vbCrLf & "Please ensure you choose a valid document to export from the dropdown provided.", vbInformation, "Invalid Selection")
  117.        
  118.         '** Show the form allowing the user to choose a section again *'
  119.        Call Functions.BeginExportDocument
  120.        
  121.         result = 3
  122.        
  123.     End If
  124.    
  125.     StartExportDocument = result
  126.  
  127. End Function
  128.  
  129. '**
  130. ' Find and select the required 'Heading 1' formatted text and the content under it
  131. '
  132. ' @param required String headingName   The 'Heading 1' formatted text to find/select
  133. '*
  134. Function SelectSection(ByVal headingName As String) As Boolean
  135.  
  136.     '** Set the result to 'False' initially *'
  137.    Dim result As Boolean
  138.     result = False
  139.    
  140.     '** Find the 'Header 1' formatted text of the required 'headingName' *'
  141.    With Selection.Find
  142.         .ClearFormatting
  143.         .Style = ActiveDocument.Styles("Heading 1")
  144.         .Text = headingName
  145.         .Forward = True
  146.         .Wrap = wdFindStop
  147.         .Format = True
  148.         .MatchCase = True
  149.         .MatchWholeWord = True
  150.         .MatchWildcards = False
  151.         .MatchSoundsLike = False
  152.         .MatchAllWordForms = False
  153.     End With
  154.    
  155.     '** Select the 'Header 1' formatted text of the required 'headingName' *'
  156.    Selection.Find.Execute
  157.  
  158.     '** Check that some 'Header 1' formatted text is selected (check only the first one if multiple paragraphs are selected). *'
  159.    If ActiveDocument.Styles(Selection.Paragraphs(1).Style).ParagraphFormat.OutlineLevel < wdOutlineLevelBodyText Then
  160.    
  161.         Dim headStyle As Style
  162.         Set headStyle = Selection.Paragraphs(Selection.Paragraphs.Count).Style
  163.         Selection.Expand wdParagraph
  164.         result = True
  165.        
  166.     Else:
  167.        
  168.         result = False
  169.        
  170.     End If
  171.    
  172.     If result = True Then
  173.    
  174.         '** Turn off screen updating (so that the screen does not flicker) *'
  175.        Application.ScreenUpdating = False
  176.        
  177.         '** Loop through the paragraphs following the selection and incorporate them into the selection (as long as they have a higher outline level than the selected heading) *'
  178.        Do While ActiveDocument.Styles(Selection.Paragraphs(Selection.Paragraphs.Count).Next.Style).ParagraphFormat.OutlineLevel > headStyle.ParagraphFormat.OutlineLevel
  179.        
  180.             Selection.MoveEnd wdParagraph
  181.             If Selection.Paragraphs(Selection.Paragraphs.Count).Next Is Nothing Then Exit Do
  182.            
  183.         Loop
  184.    
  185.     End If
  186.    
  187.     '** Turn screen updating back on *'
  188.    Application.ScreenUpdating = True
  189.    
  190.     '** Return the result of the check selection *'
  191.    SelectSection = result
  192.    
  193. End Function
  194.  
  195. '**
  196. ' Copy the selected text to a new document
  197. '
  198. ' @param required String headingName   The 'Heading 1' formated text section that is being exported (for the document name)
  199. ' @return Boolean result               Whether or not the export was successful
  200. '*
  201. Function CopyToNewDocument(ByVal headingName As String) As Boolean
  202.  
  203.     '** Set the result to 'False' initially *'
  204.    Dim result As Boolean
  205.     result = False
  206.    
  207.     '** Copy the selection *'
  208.    Selection.Copy
  209.    
  210.     '** Set the OpenDirectoy location to be that of the folder containing this document *'
  211.    Dim openDirectory As String
  212.     openDirectory = ActiveDocument.Path
  213.    
  214.     '** Set the path of the new starter template *'
  215.    Dim template As String
  216.     template = openDirectory & "\" & "NewStarterBlankTemplate.dotx"
  217.    
  218.     '** Ensure that the new starter template exists in the same directory as this document *'
  219.    
  220.     Dim tempDoc As Document
  221.     If FileExists(template) = True Then
  222.    
  223.         '** Create a new document from the new starter template to paste the copied text into *'
  224.        Set tempDoc = Documents.Add(template:=template)
  225.        
  226.     Else
  227.    
  228.         '** Create a new blank document to paste the copied text into *'
  229.        Set tempDoc = Documents.Add
  230.        
  231.     End If
  232.    
  233.     '** Paste the copied text (tempDoc will be selected by default) *'
  234.    Selection.PasteAndFormat (wdUseDestinationStylesRecovery)
  235.    
  236.     '** Set the name and path of the file to save *'
  237.    Dim fileName As String
  238.     fileName = SetFileName(openDirectory, headingName)
  239.    
  240.     '** Set the document properties so that they are applied to the PDF document *'
  241.    If Not SetProperties(tempDoc, headingName) Then
  242.         MsgBox "Unable to set 1 or more of the document properties (Export will continue).", vbInformation, "For your information..."
  243.         Debug.Print "Notice: (Functions.CopyToNewDocument) 1 or more of the document properties could not be set." & vbCrLf
  244.     End If
  245.    
  246.     '** Ensure that a fileName has been selected *'
  247.    If Not fileName = "" Then
  248.    
  249.         '** Export the document to PDF *'
  250.        ActiveDocument.ExportAsFixedFormat OutputFileName:= _
  251.             fileName, ExportFormat:= _
  252.             wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _
  253.             wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
  254.             item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
  255.             CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
  256.             BitmapMissingFonts:=True, UseISO19005_1:=False
  257.            
  258.         result = True
  259.        
  260.     End If
  261.        
  262.     '** Close the new document *'
  263.    tempDoc.Close False
  264.     Set tempDoc = Nothing
  265.    
  266.     CopyToNewDocument = result
  267.  
  268. End Function
  269.  
  270. '**
  271. ' Set the filename to save the document as
  272. '
  273. ' @param required String openDirectory The directory that the save as dialog should open in
  274. ' @param required String headingName   The 'Heading 1' section that is being exported
  275. '
  276. '*
  277. Function SetFileName(ByVal openDirectory As String, _
  278.                      ByVal headingName As String) As String
  279.  
  280.     SetFileName = ""
  281.    
  282.     '** Set up a 'Save As' dialog
  283.    Dim dlgSaveAs As FileDialog
  284.     Set dlgSaveAs = Application.FileDialog(FileDialogType:=msoFileDialogSaveAs)
  285.    
  286.     ' Show the 'Save As' dialog
  287.    With dlgSaveAs
  288.    
  289.         .Title = "Exprot to PDF"                                ' Dialog title
  290.        .InitialView = msoFileDialogViewDetails                 ' The 'view' to use in the dialog
  291.        .InitialFileName = openDirectory & "\" & headingName    ' The initial document name
  292.        .FilterIndex = 7                                        ' The initial document type (*.pdf)
  293.        
  294.         If .Show = -1 Then
  295.        
  296.             Dim SelectedItem
  297.             For Each SelectedItem In dlgSaveAs.SelectedItems
  298.                 SetFileName = SelectedItem
  299.             Next SelectedItem
  300.            
  301.         End If
  302.        
  303.     End With
  304.    
  305. End Function
  306.  
  307. '**
  308. ' Check whether or not an item exists within an array
  309. '
  310. ' @param required Variant item The item to find
  311. ' @param required Variant arr  The array to search
  312. ' @return Boolean              Whether or not 'item' existed in 'arr'
  313. '*
  314. Function InArray(ByVal item As Variant, _
  315.                  ByVal arr As Variant) As Boolean
  316.  
  317.     InArray = (UBound(Filter(arr, item)) > -1)
  318.    
  319. End Function
  320.  
  321. '**
  322. ' Check whether or not a file exists
  323. '
  324. ' @param required String file  The file to check the existnece of
  325. ' @return Boolean              Whether or not 'file' exists
  326. '*
  327. Function FileExists(ByVal file As String) As Boolean
  328.  
  329.     FileExists = (Dir(file) > "")
  330.    
  331. End Function
  332.  
  333. '**
  334. ' Set the required properties for this temporary document
  335. '
  336. ' @param required Document tempDoc     The temporary document to set properties for
  337. ' @param required String documentName  The name of the temporary document
  338. ' @return Boolean result               Whether or not setting all properties was successful
  339. '*
  340. Function SetProperties(ByRef tempDoc As Document, _
  341.                        ByVal documentName As String) As Boolean
  342.                        
  343.     Dim result As Boolean               ' Whether or not all properties have been set successfully
  344.    Dim propertyResult(2) As Boolean    ' The resultes of each individual property set
  345.  
  346.     '** Set the desired properties *'
  347.    propertyResult(0) = UpdateDocumentProperty(tempDoc, "Title", "New Starter Guide - " & documentName)
  348.     propertyResult(1) = UpdateDocumentProperty(tempDoc, "Subject", "New starter guide")
  349.     propertyResult(2) = UpdateDocumentProperty(tempDoc, "Keywords", "new starters, guide, help")
  350.  
  351.     '** Check to see if there was an error setting any of the desired properties *'
  352.    Dim i As Integer    ' Dummy for looping
  353.    For i = 0 To UBound(propertyResult)
  354.         If propertyResult(i) = False Then
  355.             result = False
  356.             Exit For
  357.         Else
  358.             result = True
  359.         End If
  360.     Next i
  361.    
  362.     SetProperties = result
  363.  
  364. End Function
  365.  
  366. '**
  367. ' Update a single property
  368. '
  369. ' @param required Document doc         The document to update a property in
  370. ' @param required String propertyName  The name of the property to update
  371. ' @param required String propertyValue The value of the property to update
  372. ' @param MsoDocProperties propertyType The property type (http://msdn.microsoft.com/en-us/library/aa432509%28v=office.12%29.aspx)
  373. ' @return Boolean result               Whether or not setting this single property was successful
  374. '*
  375. Function UpdateDocumentProperty(ByRef doc As Document, _
  376.                                 ByVal propertyName As String, _
  377.                                 ByVal propertyValue As Variant, _
  378.                                 Optional ByVal propertyType As Office.MsoDocProperties = 4)
  379.                                
  380.     '** Set the result to 'False' by default '*
  381.    Dim result As Boolean
  382.     result = False
  383.    
  384.     '** A property to hold whether or not the property used is default or custom *'
  385.    Dim propertyTypeUsed As String
  386.  
  387.     '** Check to see if the document property already exists *'
  388.    Dim propertyExists As String
  389.     propertyExists = DoesPropertyExist(doc, propertyName)
  390.    
  391.     '** Add the property to the appropriate property object *'
  392.    If propertyExists = "builtin" Then                                  ' A default property exists, so use that
  393.        doc.BuiltInDocumentProperties(propertyName).value = propertyValue
  394.         propertyTypeUsed = "default"
  395.     ElseIf propertyExists = "custom" Then                               ' A custom property exists, so use that
  396.        doc.CustomDocumentProperties(propertyName).value = propertyValue
  397.         propertyTypeUsed = "custom"
  398.     Else                                                                ' No property exists, so create a custom property
  399.        doc.CustomDocumentProperties.Add _
  400.             name:=propertyName, _
  401.             LinkToContent:=False, _
  402.             Type:=propertyType, _
  403.             value:=propertyValue
  404.         propertyTypeUsed = "custom"
  405.     End If
  406.    
  407.     '** Check whether or not the value has actually been set *'
  408.    On Error Resume Next
  409.     If propertyTypeUsed = "default" Then
  410.         result = (doc.BuiltInDocumentProperties(propertyName).value = propertyValue)
  411.     ElseIf propertyTypeUsed = "custom" Then
  412.         result = (doc.CustomDocumentProperties(propertyName).value = propertyValue)
  413.     End If
  414.     On Error GoTo 0
  415.     UpdateDocumentProperty = result
  416.    
  417. End Function
  418.  
  419. '**
  420. ' Check to see if a propery exists within a doucment
  421. '
  422. ' @param required Document doc The document to check
  423. ' @param required String name  The name of the property to check
  424. ' @return String result        In which scope the propery exists ("builtin", "custom" or "")
  425. '*
  426. Function DoesPropertyExist(ByRef doc As Document, _
  427.                            ByVal name As String) As String
  428.                        
  429.     '** Set result to "" initially *'
  430.    Dim result
  431.     result = ""
  432.    
  433.     Dim i   ' Dummy for looping
  434.    
  435.     '** Loop through each built-in property and check if the desired property exists *'
  436.    For i = 1 To doc.BuiltInDocumentProperties.Count
  437.         If doc.BuiltInDocumentProperties(i).name = name Then
  438.             result = "builtin"
  439.         End If
  440.     Next
  441.    
  442.     '** Loop through each custom property and check if the desired property exists *'
  443.    If result = "" Then
  444.         For i = 1 To doc.CustomDocumentProperties.Count
  445.             If doc.CustomDocumentProperties(i).name = name Then
  446.                 result = "custom"
  447.             End If
  448.         Next
  449.     End If
  450.    
  451.     DoesPropertyExist = result
  452.  
  453. End Function
  454.  
  455. '**
  456. ' Check the result of a document export and output any necessary errors
  457. '
  458. ' @param required Integer result   The result to check
  459. '*
  460. Sub CheckResult(ByVal result As Integer)
  461.  
  462.     Select Case result
  463.    
  464.         Case 0
  465.             Debug.Print "Warning: No result was set, so it's likely something went wrong and was handeled but not reported.  It is suggested that you start debugging..." & vbCrLf
  466.         Case 1
  467.             Debug.Print "Notice: Everything worked fine, your New Started document should have been created." & vbCrLf
  468.         Case 2
  469.             Debug.Print "Notice: (Functions.CopyToNewDocument): No 'fileName' was set, probably because the user canceled at this point, so no PDF was created." & vbCrLf
  470.         Case 3
  471.             Debug.Print "Warning: (Functions.StartExportDocument): There is no valid selection to export." & vbCrLf
  472.             Call MsgBox("Sorry, we're unable to find any text related to the New Starter document that you selected.", vbExclamation, "Text not found")
  473.            
  474.     End Select
  475.  
  476. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement