Advertisement
codeuniv

Yaroslav Macro (WORD 2002 + DOCX CONVERTER)

Feb 19th, 2019
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VBScript 15.67 KB | None | 0 0
  1. 'ADJUSTED FOR WORD 2002 + DOCX CONVERTER (THEY GARBLE HEADERS FROM DOCX AND CHANGE HEADER FONT SIZE: 20->16!)
  2. '1) SWITCH KEYBOARD/WINDOWS LANGUAGE TO RUSSIAN
  3. 'BEFORE COPYING (AND PASTING) THIS MACRO!!!
  4. '2). Word Object Model Changes (Word 2000 is VBA 6.0, Word 2010 is VBA 7.0, W2016=7.1)
  5. 'https://msdn.microsoft.com/en-us/library/office/bb149069(v=office.12).aspx
  6. Sub SMI_Monitoring_Formatter_MACRO()
  7.  
  8. 'Disable MRU Files list
  9. 'Application.RecentFiles.Maximum = 0
  10.  
  11.  
  12.     'copy-paste all into new document
  13.    Selection.WholeStory
  14.     Selection.Copy
  15.     'clear selection in orig doc to save mem
  16.    Selection.HomeKey Unit:=wdStory 'go home (top)
  17.    Documents.Add DocumentType:=wdNewBlankDocument
  18.     Selection.PasteAndFormat (wdUseDestinationStylesRecovery)
  19.     'Clear Undo history for THIS doc ONLY
  20.    'b/c huge copied text chunk clogs memory
  21.    ActiveDocument.UndoClear
  22.    
  23.    
  24.     ' check MS Word version
  25.    ' CURRENTLY NOT USED
  26.    Select Case Application.Version
  27.      Case "16.0"
  28.        msWordVersion = "MS Word 2016 / Office 365 / Word 2019"
  29.     Case "15.0"
  30.        msWordVersion = "MS Word 2013"
  31.     Case "14.0"
  32.         msWordVersion = "MS Word 2010"
  33.     ' 13.0 is missing  (Microsoft skipped 13)
  34.    Case "12.0"
  35.         msWordVersion = "MS Word 2007"
  36.     Case "11.0"
  37.         msWordVersion = "MS Word 2003"
  38.     Case "10.0"
  39.         msWordVersion = "MS Word 2002 (aka  Word XP)"
  40.     Case "9.0"
  41.         msWordVersion = "MS Word 2000"
  42.     Case "8.0"
  43.         msWordVersion = "MS Word 97"
  44.     Case "7.0"
  45.         msWordVersion = "MS Word 95"
  46.     End Select
  47.    
  48.    
  49.     'Application.System.Version RETURNS:
  50.    ' "6.1" on Windows 7 and "6.2" on Windows 8
  51.    ' 10.0 on Windows 10
  52.              
  53. '*******************************************************************
  54. '********MAIN LOGIC START*******************************************
  55. '*******************************************************************
  56.    
  57.     'position cursor at HOME (doc start)
  58.    Selection.HomeKey Unit:=wdStory 'go home (top)
  59.    
  60.     'check if doc-to-process has TOC => check 3 markers:
  61.    
  62.     'check FirstMarkerPhrase
  63.    Selection.Find.ClearFormatting
  64.     With Selection.Find.Font
  65.         .Bold = True
  66.     End With
  67.     With Selection.Find
  68.         .Text = "Департамент корпоративных коммуникаций"
  69.         .Replacement.Text = ""
  70.         .Forward = True
  71.         .Wrap = wdFindContinue
  72.     End With
  73.    isHasFirstMarkerPhrase = Selection.Find.Execute
  74.    
  75.    '.Text = "Департаменткорпоративныхкоммуникаций" глюк
  76.   If isHasFirstMarkerPhrase = False Then
  77.        Selection.Find.ClearFormatting
  78.     With Selection.Find.Font
  79.         .Bold = True
  80.     End With
  81.     With Selection.Find
  82.         .Text = "Департаменткорпоративныхкоммуникаций"
  83.         .Replacement.Text = ""
  84.         .Forward = True
  85.         .Wrap = wdFindContinue
  86.     End With
  87.     isHasFirstMarkerPhrase = Selection.Find.Execute
  88.    End If
  89.    
  90.     'check SecondMarkerPhrase
  91.    Selection.HomeKey Unit:=wdStory 'go home (top)
  92.    
  93.     Selection.Find.ClearFormatting
  94.     With Selection.Find.Font
  95.         .Bold = True
  96.     End With
  97.     With Selection.Find
  98.         .Text = "МОНИТОРИНГ СМИ"
  99.         .Replacement.Text = ""
  100.         .Forward = True
  101.         .Wrap = wdFindContinue
  102.     End With
  103.    isHasSecondMarkerPhrase = Selection.Find.Execute
  104.    
  105.    '.Text = "МОНИТОРИНГСМИ" глюк
  106.   If isHasSecondMarkerPhrase = False Then
  107.     Selection.Find.ClearFormatting
  108.     With Selection.Find.Font
  109.         .Bold = True
  110.     End With
  111.     With Selection.Find
  112.         .Text = "МОНИТОРИНГСМИ"
  113.         .Replacement.Text = ""
  114.         .Forward = True
  115.         .Wrap = wdFindContinue
  116.     End With
  117.     isHasSecondMarkerPhrase = Selection.Find.Execute
  118.    End If
  119.    
  120.    
  121.    'check ThirdMarker - Column Separator
  122.    Selection.HomeKey Unit:=wdStory 'go home (top)
  123.    
  124.    Selection.Find.ClearFormatting
  125.     With Selection.Find
  126.         .Text = "^n"
  127.         .Replacement.Text = ""
  128.         .Forward = True
  129.         .Wrap = wdFindContinue
  130.         .Format = False
  131.     End With
  132.     isHasThirdMarker = Selection.Find.Execute
  133.    
  134.     'Remove TOC (if doc-to-process has any TOC)
  135.    If isHasFirstMarkerPhrase And isHasSecondMarkerPhrase And isHasThirdMarker Then
  136.     Selection.Find.ClearFormatting
  137.     With Selection.Find
  138.         .Text = "^n"
  139.         .Replacement.Text = ""
  140.         .Forward = True
  141.         .Wrap = wdFindContinue
  142.         .Format = False
  143.         .MatchCase = False
  144.         .MatchWholeWord = False
  145.         .MatchWildcards = False
  146.         .MatchSoundsLike = False
  147.         .MatchAllWordForms = False
  148.     End With
  149.     Selection.Find.Execute
  150.     Selection.HomeKey Unit:=wdStory, Extend:=wdExtend
  151.     Selection.Delete Unit:=wdCharacter, Count:=1
  152.     Selection.Delete Unit:=wdCharacter, Count:=1
  153.     End If
  154.    
  155.    
  156.     ' BELOW PROCESSING LOGIC IS SAME FOR ANY DOCUMENT
  157.    '***************************************************************************
  158.    
  159.     Dim articleCounter As Integer
  160.    
  161.     'position cursor at HOME (doc start)
  162.    Selection.HomeKey Unit:=wdStory
  163.    
  164.     Dim isMoreMainHeadersPresent As Boolean 'defaults to FALSE
  165.    
  166.     'loop all MAIN HEADERs and
  167.    'process ONLY first article after each MAIN HEADER.
  168.    'Add no empty paragraphs as separators!
  169.    Do
  170. 'FIND MAIN HEADER
  171. '1.1. setup search
  172.        Selection.Find.ClearFormatting
  173.         With Selection.Find.Font
  174.             .Size = 20
  175.             .Bold = True
  176.             .Italic = True
  177.             .Underline = True
  178.             .Name = "Georgia"
  179.         End With
  180. '1.2. do search (for main header).
  181. 'search formatting only: FindText:=""
  182.        isMoreMainHeadersPresent = Selection.Find.Execute(FindText:="")
  183.        
  184.         'ГЛЮК: Word 2002 + docx plugin Font Size is 16, not 20 (as in higher Word) !!!
  185.        If isMoreMainHeadersPresent = False Then
  186.             Selection.Find.Font.Size = 16
  187.             isMoreMainHeadersPresent = Selection.Find.Execute(FindText:="")
  188.         End If
  189.        
  190.        
  191.         If isMoreMainHeadersPresent Then
  192.            
  193. 'DELETE FOUND MAIN HEADER
  194.            Selection.Delete
  195.            
  196. 'select line/para immediately after deleted MAIN HEADER
  197. '(including paragraph sign)
  198.            Selection.Expand wdParagraph
  199.             'Selection.EndKey Unit:=wdLine, Extend:=wdExtend 'Fails with multi-line para
  200.  
  201. 'PARSE/FIND: http://on-line-teaching.com/vba/lsn0107.html
  202.            
  203. 'parse article header
  204. '(save the line/para selected above to variable)
  205.            initialTitleStr = Selection.Range.Text
  206. 'construct wanted title string.
  207. '( _SERVICE$SOURCE#MARK_ will be replaced
  208. 'to "Заглавие:  " + 2 preceeding para marks later)
  209.            resultingTitleStr = "Заглавие: " + initialTitleStr
  210. 'Delete (previously selected) header line (paragraph)
  211.            Selection.Delete
  212.            
  213. 'select line/para immediately after deleted
  214. 'article header line (including paragraph sign)
  215.            Selection.Expand wdParagraph
  216.             'Selection.EndKey Unit:=wdLine, Extend:=wdExtend
  217.            
  218.             initiaDateAndSourceString = Selection.Range.Text
  219.             parsedDate = Left(initiaDateAndSourceString, InStr(initiaDateAndSourceString, ",") - 1)
  220.             parsedSource = Mid(initiaDateAndSourceString, InStr(initiaDateAndSourceString, ",") + 1)
  221.            
  222.             resultingDateAndSourceText = "_SERVICE$SOURCE#MARK_" + parsedSource
  223.            
  224.             resultingDateAndSourceText = resultingDateAndSourceText + "Дата выпуска: " + parsedDate + vbCrLf
  225.            
  226.             Selection.Range.Text = resultingDateAndSourceText + resultingTitleStr
  227.            
  228.             articleCounter = articleCounter + 1
  229.            
  230.         End If
  231.     Loop While isMoreMainHeadersPresent
  232.    
  233.    
  234.    
  235.     'Now loop Headers of Remaining Articles
  236.    'process all respective articles
  237.    'Add no empty paragraphs as separators!
  238.    Selection.HomeKey Unit:=wdStory 'GO HOME (top of file) FIRST TO SEARCH FROM BEGINNING
  239.    
  240.     Do
  241. 'FIND Article header
  242. '1.1. setup search
  243.        Selection.Find.ClearFormatting
  244.          With Selection.Find.ParagraphFormat
  245.         .SpaceBefore = 12
  246.     End With
  247. '1.2. do search (for regular article header).
  248. 'search formatting only: FindText:=""
  249.        isMoreArticleHeadersPresent = Selection.Find.Execute(FindText:="")
  250.        
  251.         If isMoreArticleHeadersPresent Then
  252.            
  253. 'parse article header
  254. '(save the line/para selected above to variable)
  255.            initialTitleStr = Selection.Range.Text
  256. 'construct wanted title string.
  257. '( _SERVICE$SOURCE#MARK_ will be replaced
  258. 'to "Заглавие:  " + 2 preceeding para marks later)
  259.            resultingTitleStr = "Заглавие: " + initialTitleStr
  260. 'Delete (previously selected) header line (paragraph)
  261.            Selection.Delete
  262.            
  263. 'select line/para immediately after deleted
  264. 'article header line (including paragraph sign)
  265.            Selection.Expand wdParagraph
  266.             'Selection.EndKey Unit:=wdLine, Extend:=wdExtend
  267.            
  268.             initiaDateAndSourceString = Selection.Range.Text
  269.             Dim dateSplitLengthFromLeft As Long
  270.             dateSplitLengthFromLeft = InStr(initiaDateAndSourceString, ",") - 1
  271.             parsedDate = Left(initiaDateAndSourceString, dateSplitLengthFromLeft)
  272.             parsedSource = Mid(initiaDateAndSourceString, InStr(initiaDateAndSourceString, ",") + 1)
  273.            
  274.             resultingDateAndSourceText = "_SERVICE$SOURCE#MARK_" + parsedSource
  275.            
  276.             resultingDateAndSourceText = resultingDateAndSourceText + "Дата выпуска: " + parsedDate + vbCrLf
  277.            
  278.             Selection.Range.Text = resultingDateAndSourceText + resultingTitleStr
  279.            
  280.             articleCounter = articleCounter + 1
  281.            
  282.         End If
  283.     Loop While isMoreArticleHeadersPresent
  284.    
  285.    
  286.    
  287.     'Now Replace
  288.    '_SERVICE$SOURCE#MARK_
  289.    'to "Заглавие:  " + add 2 preceeding para marks)
  290.    Selection.HomeKey Unit:=wdStory  'GO HOME (top of file) - not neccesary, but just in case
  291.    'Replace
  292.        Selection.Find.ClearFormatting
  293.     Selection.Find.Replacement.ClearFormatting
  294.     With Selection.Find
  295.         .Text = "_SERVICE$SOURCE#MARK_"
  296.         .Replacement.Text = "^p^pИсточник:"
  297.         .Forward = True
  298.         .Wrap = wdFindContinue
  299.         .Format = False
  300.         .MatchCase = True
  301.     End With
  302.     Selection.Find.Execute Replace:=wdReplaceAll
  303.    
  304.    
  305.      Selection.HomeKey Unit:=wdStory 'go home - top of doc
  306.     'delete 2 empty para
  307.     Selection.Delete Unit:=wdCharacter, Count:=1
  308.      Selection.Delete Unit:=wdCharacter, Count:=1
  309.    
  310.     'Format all text
  311.    Selection.WholeStory 'ctrl+A : select all text
  312.    ' format font
  313.    With Selection.Font
  314.     .Name = "Times New Roman"
  315.      .Size = 12
  316.         .Bold = False
  317.         .Italic = False
  318.         .Underline = wdUnderlineNone
  319.         .StrikeThrough = False
  320.         .DoubleStrikeThrough = False
  321.         .Hidden = False
  322.         .SmallCaps = False
  323.         .AllCaps = False
  324.         .Color = wdColorAutomatic
  325.         .Superscript = False
  326.         .Subscript = False
  327.         .Scaling = 100
  328.         .Kerning = 0
  329.     End With
  330.     'format paragrgraph
  331.    With Selection.ParagraphFormat
  332.         .LeftIndent = CentimetersToPoints(0)
  333.         .RightIndent = CentimetersToPoints(0)
  334.         .SpaceBefore = 0
  335.         .SpaceBeforeAuto = False
  336.         .SpaceAfter = 0
  337.         .SpaceAfterAuto = False
  338.         .LineSpacingRule = wdLineSpaceSingle
  339.         .Alignment = wdAlignParagraphLeft
  340.         .FirstLineIndent = CentimetersToPoints(0)
  341.         .OutlineLevel = wdOutlineLevelBodyText
  342.         .CharacterUnitLeftIndent = 0
  343.         .CharacterUnitRightIndent = 0
  344.         .CharacterUnitFirstLineIndent = 0
  345.         .LineUnitBefore = 0
  346.         .LineUnitAfter = 0
  347.     End With
  348.  
  349.     'Delete all headers and footers (колонтитулы)
  350.    Dim oSec As Section
  351.     Dim oHead As HeaderFooter
  352.     Dim oFoot As HeaderFooter
  353.  
  354.     For Each oSec In ActiveDocument.Sections
  355.         For Each oHead In oSec.Headers
  356.             If oHead.Exists Then oHead.Range.Delete
  357.         Next oHead
  358.  
  359.         For Each oFoot In oSec.Footers
  360.             If oFoot.Exists Then oFoot.Range.Delete
  361.         Next oFoot
  362.     Next oSec
  363.    
  364.   'войти в верхний колонтитул и удалить пустой параграф
  365.  ' чтобы не показывал пустой параграф в уже удаленных колонтитулах
  366.  ' Вообще это глюк, колонтитулов уже быть не должно (100% пустые быть должны)*
  367.  '*(колонтитулы есть ВСЕГДА - даже во вновь созданном док-те
  368.        If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
  369.         ActiveWindow.Panes(2).Close
  370.     End If
  371.     If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
  372.         ActivePane.View.Type = wdOutlineView Then
  373.         ActiveWindow.ActivePane.View.Type = wdPrintView
  374.     End If
  375.     ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
  376.     Selection.WholeStory
  377.     Selection.Delete Unit:=wdCharacter, Count:=1
  378.     ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
  379.    
  380.    
  381.     'find some text to be present for sure
  382.    'and put it into Windows Clipboard
  383.    'to clear it from bulky document content
  384.    Selection.Find.ClearFormatting
  385.     With Selection.Find
  386.         .Text = "Источник"
  387.         .Replacement.Text = ""
  388.         .Forward = True
  389.         .Wrap = wdFindContinue
  390.         .Format = False
  391.         .MatchCase = False
  392.         .MatchWholeWord = False
  393.         .MatchWildcards = False
  394.         .MatchSoundsLike = False
  395.         .MatchAllWordForms = False
  396.     End With
  397.     Selection.Find.Execute
  398.     Selection.Copy
  399.    
  400.     'Clear Undo history for THIS doc ONLY
  401.    'to save free memory
  402.    ActiveDocument.UndoClear
  403.    
  404.     'go home - top of doc
  405.    Selection.HomeKey Unit:=wdStory
  406.    
  407.     ' Show user number of processed articles
  408.    ' Offer user to save current processed doc
  409.    Dim Msg, Style, Title, Help, Ctxt, Response, MyString
  410.     Msg = articleCounter & " articles processed (total)." & vbCrLf & vbCrLf & "DO YOU WANT TO SAVE RESULTS?"     ' Define message.
  411.    Style = vbOKCancel + vbInformation + vbDefaultButton1   ' Define buttons
  412.    Title = "MACRO FINISHED AUTO-FORMATTING"    ' Define title
  413.        ' Display message.
  414.    Response = MsgBox(Msg, Style, Title)
  415.     If Response = vbOK Then    ' User chose OK:
  416.        'offer to save (user inputs path himself)
  417.        defaultFileNameToSave = "Мониторинг СМИ_" & Date & "_macroProcessed"
  418.         Application.FileDialog(msoFileDialogSaveAs).InitialFileName = defaultFileNameToSave
  419.         Dim choice As Integer
  420.         choice = Application.FileDialog(msoFileDialogSaveAs).Show
  421.         If choice <> 0 Then
  422.             FileName = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
  423.             Application.FileDialog(msoFileDialogSaveAs).Execute
  424.         End If
  425.     Else    ' User chose Cancel:
  426.       ' end of macro
  427.    End If
  428.    
  429.     'Clear Clipboard (sometimes works, but not with Word 2002, not Word 2016)
  430.    If Application.Version = "10.0" Then
  431.     'it was possible to manipulate the Office Clipboard Toolbar in Word 2000, not later
  432.    'Application.CutCopyMode = False ' no longer works in 2010
  433.  
  434.     'SECOND TRICK (only early word)
  435.    'Dim oData As New DataObject 'object to use the clipboard
  436.    'oData.SetText Text:=Empty 'Clear
  437.    'oData.PutInClipboard 'take in the clipboard to empty it
  438.    
  439.     End If
  440.    
  441. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement