Advertisement
duck__boy1981

VBA - Format document for web publishing

Mar 14th, 2013
1,196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Option Explicit
  2.  
  3. Public Sub start_tla()
  4.  
  5.     Dim formatted As Boolean        ' Whether or not the document is already formatted for publishing
  6.    Dim document_title As String    ' The title of the current document
  7.  
  8.     ' Set up the error handling
  9.    On Error GoTo error
  10.    
  11.     Application.ScreenUpdating = False
  12.    
  13.     ' Show the 'Please wait' form
  14.    TLA_formatting.Show False
  15.    
  16.     ' Move the cursor to the beginning of the document
  17.    Selection.GoTo wdGoToBookmark, , , "\StartOfDoc"
  18.    
  19.     ' Check to see if the document has already been formatted for publishing
  20.    formatted = check_if_formatted
  21.     If formatted = True Then GoTo finish
  22.    
  23.     ' Remove any empty paragraphs
  24.    Call remove_empty_paragraphs
  25.    
  26.     ' Format the tile
  27.    document_title = get_title
  28.    
  29.     ' Format the paragraphs
  30.    Call format_paragraphs
  31.    
  32.     ' Set the document properties
  33.    Call set_document_properties(document_title)
  34.    
  35.     ' Set the zoom to 100%
  36.    ActiveWindow.ActivePane.View.Zoom.Percentage = 100
  37.    
  38.     ' Save the document
  39.    If ActiveDocument.Path = vbNullString Then
  40.         Application.Dialogs(wdDialogFileSaveAs).Show
  41.     Else
  42.         ActiveDocument.Save
  43.     End If
  44.    
  45.     ' Reset the error handling
  46.    On Error GoTo 0
  47.    
  48. error:
  49.     If Err.Number <> 0 Then
  50.        
  51.         Dim error_msg As String
  52.        
  53.         error_msg = "An error occured while trying to format this document. Please undo any changes and try again"
  54.         error_msg = error_msg & vbCrLf & vbCrLf & "Error number: " & Err.Number
  55.         error_msg = error_msg & vbCrLf & "Error number: " & Err.Description
  56.                
  57.         MsgBox error_msg, vbOKOnly, "An error has occured"
  58.        
  59.     End If
  60.    
  61. finish:
  62.    
  63.     ' Hide the 'Please wait' form
  64.    TLA_formatting.Hide
  65.  
  66.     ' If the doucment has alredy been formatted for publishing, show a message box to tell the user
  67.    If formatted = True Then MsgBox "This document has already been formatted for publishing", vbOKOnly, "Document Ready For Publishing"
  68.    
  69.     Application.ScreenUpdating = True
  70.  
  71. End Sub
  72.  
  73. '**
  74. ' Checks to see if a document has already been formatted for publishing
  75. '*
  76. Function check_if_formatted()
  77.  
  78.     check_if_formatted = (ActiveDocument.BuiltInDocumentProperties("Content status").Value = "ready")
  79.  
  80. End Function
  81.  
  82. '**
  83. ' Removes any paragraphs that are empty in the document
  84. '*
  85. Function remove_empty_paragraphs(Optional trim_string As Boolean = True)
  86.    
  87.     Dim para As Paragraph
  88.    
  89.     For Each para In ActiveDocument.Paragraphs
  90.    
  91.         ' Trim the text
  92.        'If trim_string = True Then
  93.            'para.Range.Text = trim(para.Range.Text)
  94.        'End If
  95.        
  96.         ' Check if the length of the paragraph is 1 - if so, it can be deleted
  97.        If Len(para.Range.Text) = 1 Then
  98.             para.Range.Delete
  99.         End If
  100.    
  101.     Next
  102.  
  103. End Function
  104.  
  105. '**
  106. ' Formats the title correctly
  107. '*
  108. Function get_title() As String
  109.    
  110.     Dim para As Paragraph
  111.  
  112.     ' Set para as the first paragraph (The title)
  113.    Set para = ActiveDocument.Paragraphs.First
  114.    
  115.     ' Set 'Heading 1' to the desired format
  116.    Call set_heading_1
  117.    
  118.     ' Format the paragraph to 'Heading 1'
  119.    para.Format.Style = ActiveDocument.Styles("Heading 1")
  120.    
  121.     get_title = para.Range.Text
  122.  
  123. End Function
  124.  
  125. '**
  126. ' Adds the '<br />' code in between paragraphs
  127. '*
  128. Function format_paragraphs()
  129.  
  130.     Dim para As Paragraph           ' A paragraph object used for looping through paragraphs
  131.    Dim temp_range As Range         ' The temporty range of the paragraph that is being looped (so the ending '</li>' is placed in the correct place)
  132.    Dim is_list_item As Boolean     ' Whether or not a paragraph is part of a list
  133.    Dim was_list_item As Boolean    ' Whether or not the previous paragraph was a list item
  134.    Dim open_list As String         ' The open tag to insert before the paragraph(if it is the first item in a list)
  135.    Dim close_list As String        ' The close tag to insert after the paragraph (if it is the last item in a list)
  136.    Dim i As Integer                ' Dummy for looping and counting
  137.    
  138.     i = 0
  139.    
  140.     ' Set 'Normal' to the desired format
  141.    Call set_normal
  142.    
  143.     ' Loop through all paragraphs
  144.    For Each para In ActiveDocument.Paragraphs
  145.        
  146.         ' Checks whether or not the previous item was a list item (so that a '</ul>' can be inserted, instead of a '<br />')
  147.        If is_list_item = True Then
  148.             was_list_item = True
  149.         Else
  150.             was_list_item = False
  151.         End If
  152.        
  153.         ' Set 'is_list_item' to false at the beginning of each itteration
  154.        is_list_item = False
  155.        
  156.         Select Case para.Range.ListFormat.ListType
  157.        
  158.             Case WdListType.wdListBullet, _
  159.                 WdListType.wdListPictureBullet:
  160.  
  161.                 is_list_item = True
  162.                 Set temp_range = ActiveDocument.Range(para.Range.Start, para.Range.End - 1)
  163.                 temp_range.InsertBefore "<li>"
  164.                 temp_range.InsertAfter "</li>"
  165.                 open_list = "<ul>"
  166.                 close_list = "</ul>"
  167.                
  168.             Case WdListType.wdListSimpleNumbering, _
  169.                 WdListType.wdListListNumOnly, _
  170.                 WdListType.wdListMixedNumbering, _
  171.                 WdListType.wdListOutlineNumbering:
  172.  
  173.                 is_list_item = True
  174.                 Set temp_range = ActiveDocument.Range(para.Range.Start, para.Range.End - 1)
  175.                 temp_range.InsertBefore "<li>"
  176.                 temp_range.InsertAfter "</li>"
  177.                 open_list = "<ol>"
  178.                 close_list = "</ol>"
  179.  
  180.         End Select
  181.        
  182.         ' Format the paragraph to 'Normal' (if it is not the title)
  183.        If para.Format.Style <> "Heading 1" Then
  184.             para.Format.Style = ActiveDocument.Styles("Normal")
  185.         End If
  186.        
  187.         ' Add '<br />' and then a carridge return before the paragraph
  188.        If i > 1 And is_list_item = False And was_list_item = False Then ' Skip the title (picked up as a parapraph) and the first paragraph, as well as lists
  189.        
  190.             ' Add '<br />' and then a carridge return before the paragraph
  191.            para.Range.InsertBefore "<br />" & vbCrLf
  192.        
  193.         End If
  194.        
  195.         ' Check to see if the paragraph is the first or last item in a list
  196.        If is_list_item = True And was_list_item = False Then ' Add a list opening tag if the previous item was not a list, but the current one is
  197.            para.Range.InsertBefore open_list & vbCrLf
  198.         ElseIf is_list_item = False And was_list_item = True Then ' Add a list ending tag if the previous item was a list, but not the current
  199.            para.Range.InsertBefore close_list & vbCrLf
  200.         End If
  201.        
  202.         i = i + 1
  203.  
  204.     Next
  205.    
  206.     ' Add a carridge return after the title
  207.    Set para = ActiveDocument.Paragraphs.First
  208.     para.Range.InsertAfter vbCrLf
  209.  
  210. End Function
  211.  
  212. '**
  213. ' Sets the 'Heading 1' style for this document
  214. '*
  215. Function set_document_properties(Optional document_title As String = "TLA Artilce")
  216.  
  217.     ' Set the 'Built In' properties
  218.    ActiveDocument.BuiltInDocumentProperties("Title").Value = document_title
  219.     ActiveDocument.BuiltInDocumentProperties("Subject").Value = "TLA Article"
  220.     ActiveDocument.BuiltInDocumentProperties("Author").Value = "The Legal Alliance"
  221.     ActiveDocument.BuiltInDocumentProperties("Company").Value = "Dyne Drewett Solicitors Limited"
  222.     ActiveDocument.BuiltInDocumentProperties("Category").Value = "TLA-article"
  223.     ActiveDocument.BuiltInDocumentProperties("Keywords").Value = "TLA, auto-formatted"
  224.     ActiveDocument.BuiltInDocumentProperties("Content status").Value = "ready"
  225.    
  226.     ' Declare variable for adding 'Custom' properties
  227.    Dim custom_properties(0, 2) As String   ' The custom properties to add to this document
  228.    Dim custom_value As String              ' The current value of the custom property
  229.    Dim this_name As String                 ' The name of the current custom property that is being looped
  230.    Dim this_value As String                ' The value to set for the current custom property that is being looped
  231.    Dim this_type As String                 ' The type of the data to set for the current custom property that is being looped
  232.    Dim i As Integer                        ' Dummy for looping and counting
  233.    
  234.     ' Set constants for arrays
  235.    Const property_name = 0
  236.     Const property_value = 1
  237.     Const property_type = 2
  238.    
  239.     ' Set Custom property names and values
  240.    custom_properties(0, property_name) = "Date completed"
  241.     custom_properties(0, property_value) = Day(Date) & "/" & Month(Date) & "/" & Year(Date)
  242.     custom_properties(0, property_type) = msoPropertyTypeDate
  243.    
  244.     ' Loop through all of the custom properties
  245.    For i = 0 To UBound(custom_properties)
  246.        
  247.         ' Set the name and required value for this custom property
  248.        this_name = custom_properties(i, property_name)
  249.         this_value = custom_properties(i, property_value)
  250.         this_type = custom_properties(i, property_type)
  251.        
  252.         ' Check to see if the custom property exists
  253.        On Error Resume Next
  254.         custom_value = ActiveDocument.CustomDocumentProperties(this_name)
  255.         If Err.Number <> 0 Then custom_value = "null"
  256.         On Error GoTo 0
  257.    
  258.         ' Polpulate the custom property
  259.        If custom_value = "" Or custom_value = "null" Then ' Create the custom property
  260.            ActiveDocument.CustomDocumentProperties.Add _
  261.                 Name:=this_name, _
  262.                 LinkToContent:=False, _
  263.                 Value:=this_value, _
  264.                 Type:=this_type
  265.         Else ' Overwrite the custom property
  266.           ActiveDocument.CustomDocumentProperties("Date completed").Value = this_value
  267.         End If
  268.    
  269.     Next
  270.    
  271. End Function
  272.  
  273. '**
  274. ' Sets the 'Heading 1' style for this document
  275. '*
  276. Function set_heading_1()
  277.  
  278.     With ActiveDocument.Styles("Heading 1").Font
  279.         .Name = "+Headings"
  280.         .Size = 14
  281.         .Bold = True
  282.         .Italic = False
  283.         .Underline = wdUnderlineNone
  284.         .UnderlineColor = wdColorAutomatic
  285.         .StrikeThrough = False
  286.         .DoubleStrikeThrough = False
  287.         .Outline = False
  288.         .Emboss = False
  289.         .Shadow = False
  290.         .Hidden = False
  291.         .SmallCaps = False
  292.         .AllCaps = False
  293.         .Color = wdColorAutomatic
  294.         .Engrave = False
  295.         .Superscript = False
  296.         .Subscript = False
  297.         .Scaling = 100
  298.         .Kerning = 16
  299.         .Animation = wdAnimationNone
  300.     End With
  301.     With ActiveDocument.Styles("Heading 1").ParagraphFormat
  302.         .LeftIndent = CentimetersToPoints(0)
  303.         .RightIndent = CentimetersToPoints(0)
  304.         .SpaceBefore = 0
  305.         .SpaceBeforeAuto = False
  306.         .SpaceAfter = 0
  307.         .SpaceAfterAuto = False
  308.         .LineSpacingRule = wdLineSpaceMultiple
  309.         .LineSpacing = LinesToPoints(1.15)
  310.         .Alignment = wdAlignParagraphLeft
  311.         .WidowControl = True
  312.         .KeepWithNext = True
  313.         .KeepTogether = False
  314.         .PageBreakBefore = False
  315.         .NoLineNumber = False
  316.         .Hyphenation = True
  317.         .FirstLineIndent = CentimetersToPoints(0)
  318.         .OutlineLevel = wdOutlineLevel1
  319.         .CharacterUnitLeftIndent = 0
  320.         .CharacterUnitRightIndent = 0
  321.         .CharacterUnitFirstLineIndent = 0
  322.         .LineUnitBefore = 0
  323.         .LineUnitAfter = 0
  324.         .MirrorIndents = False
  325.         .TextboxTightWrap = wdTightNone
  326.     End With
  327.     ActiveDocument.Styles("Heading 1").NoSpaceBetweenParagraphsOfSameStyle = False
  328.     With ActiveDocument.Styles("Heading 1")
  329.         .AutomaticallyUpdate = True
  330.         .BaseStyle = "Normal"
  331.         .NextParagraphStyle = "Normal"
  332.     End With
  333.  
  334. End Function
  335.  
  336. '**
  337. ' Sets the 'Normal' style for this document
  338. '*
  339. Function set_normal()
  340.  
  341.     With ActiveDocument.Styles("Normal").Font
  342.         .Name = "+Body"
  343.         .Size = 11
  344.         .Bold = False
  345.         .Italic = False
  346.         .Underline = wdUnderlineNone
  347.         .UnderlineColor = wdColorAutomatic
  348.         .StrikeThrough = False
  349.         .DoubleStrikeThrough = False
  350.         .Outline = False
  351.         .Emboss = False
  352.         .Shadow = False
  353.         .Hidden = False
  354.         .SmallCaps = False
  355.         .AllCaps = False
  356.         .Color = wdColorAutomatic
  357.         .Engrave = False
  358.         .Superscript = False
  359.         .Subscript = False
  360.         .Scaling = 100
  361.         .Kerning = 0
  362.         .Animation = wdAnimationNone
  363.     End With
  364.     With ActiveDocument.Styles("Normal").ParagraphFormat
  365.         .LeftIndent = CentimetersToPoints(0)
  366.         .RightIndent = CentimetersToPoints(0)
  367.         .SpaceBefore = 0
  368.         .SpaceBeforeAuto = False
  369.         .SpaceAfter = 0
  370.         .SpaceAfterAuto = False
  371.         .LineSpacingRule = wdLineSpaceMultiple
  372.         .LineSpacing = LinesToPoints(1.15)
  373.         .Alignment = wdAlignParagraphLeft
  374.         .WidowControl = True
  375.         .KeepWithNext = False
  376.         .KeepTogether = False
  377.         .PageBreakBefore = False
  378.         .NoLineNumber = False
  379.         .Hyphenation = True
  380.         .FirstLineIndent = CentimetersToPoints(0)
  381.         .OutlineLevel = wdOutlineLevelBodyText
  382.         .CharacterUnitLeftIndent = 0
  383.         .CharacterUnitRightIndent = 0
  384.         .CharacterUnitFirstLineIndent = 0
  385.         .LineUnitBefore = 0
  386.         .LineUnitAfter = 0
  387.         .MirrorIndents = False
  388.         .TextboxTightWrap = wdTightNone
  389.     End With
  390.     ActiveDocument.Styles("Normal").NoSpaceBetweenParagraphsOfSameStyle = False
  391.     With ActiveDocument.Styles("Normal")
  392.         .AutomaticallyUpdate = True
  393.         .BaseStyle = ""
  394.         .NextParagraphStyle = "Normal"
  395.     End With
  396.  
  397. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement