Advertisement
adamsys

split_docx

Jul 28th, 2015
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Sub testFileSplit()
  2.     Call SplitNotes("///", "C:\Users\myPath\temp_DEL_008_000.docx")
  3. End Sub
  4. Sub SplitNotes(strDelim As String, strFilename As String)
  5.     Dim docNew As Document
  6.     Dim i As Long
  7.     Dim colNotes As Collection
  8.     Dim temp As Range
  9.  
  10.     'get the collection of ranges
  11.    Set colNotes = fGetCollectionOfRanges(ActiveDocument, strDelim)
  12.  
  13.     'see if the user wants to proceed
  14.    If MsgBox("This will split the document into " & _
  15.     colNotes.Count & _
  16.     " sections. Do you wish to proceed?", vbYesNo) = vbNo Then
  17.         Exit Sub
  18.     End If
  19.  
  20.      'go through the collection of ranges
  21.    For i = 1 To colNotes.Count
  22.          'create a new document
  23.        Set docNew = Documents.Add
  24.  
  25.         'copy our range
  26.        colNotes(i).Copy
  27.          'paste it in
  28.        docNew.Content.Paste
  29.          'save it
  30.        docNew.SaveAs fileName:=ThisDocument.path & "\" & strFilename & Format(i, "000"), FileFormat:=wdFormatDocument
  31.  
  32.         docNew.Close
  33.     Next
  34. End Sub
  35. Function fGetCollectionOfRanges(oDoc As Document, strDelim As String) As Collection
  36.     Dim colReturn As Collection
  37.     Dim rngSearch As Range
  38.     Dim rngFound As Range
  39.  
  40.      'initialize a new collection
  41.    Set colReturn = New Collection
  42.      'initialize our starting ranges
  43.    Set rngSearch = oDoc.Content
  44.     Set rngFound = rngSearch.Duplicate
  45.  
  46.      'start our loop
  47.    Do
  48.          'search through
  49.        With rngSearch.Find
  50.             .Text = strDelim
  51.             .Execute
  52.              'if we found it... prepare to add to our collection
  53.            If .Found Then
  54.                  'redefine our rngfound
  55.                rngFound.End = rngSearch.Start
  56.                  'add it to our collection
  57.                colReturn.Add rngFound.Duplicate
  58.                  'reset our search and found for the next
  59.                rngSearch.Collapse wdCollapseEnd
  60.                 rngFound.Start = rngSearch.Start
  61.                 rngSearch.End = oDoc.Content.End
  62.             Else
  63.                  'if we didn't find, exit our loop
  64.                Exit Do
  65.             End If
  66.         End With
  67.          'shouldn't ever hit this... unless the delimter passed in is a VBCR
  68.    Loop Until rngSearch.Start >= ActiveDocument.Content.End
  69.  
  70.      'and return our collection
  71.    Set fGetCollectionOfRanges = colReturn
  72. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement