Advertisement
codeuniv

Jaroslav Macro 2019 (Deletes date) ver 24/02/2019

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