Using Find in Word from a List in Excel VBA - vba

I am working on an automated peer review macro that would check for certain words and highlight them in a Microsoft Word document. However, I am looking to substitute the WordList = Split(" is , are ,", ",") with a list I created in excel. This would be easier for me to add new words instead of manually typing the words I want highlighted in the code.
For example: A1 has the word " is ", so I am hoping it would be something like Wordlist = Split("A1, A2")
or something like Exlist = Range("A1:A2").value so WordList = Split(ExList)
Is something like that possible? Thank you for your help.
Sub PeerReview()
Dim r As Range
Dim WordList() As String
Dim a As Long
Dim Doc As Document
Dim Response As Integer
'This code will search through all of the open word documents and ask you which ones you would like to peer review.
For Each Doc In Documents
'MsgBox Doc
Response = MsgBox(prompt:="Do you want to peer review " & Doc & "?", Buttons:=vbYesNo)
If Response = vbNo Then GoTo ShortCut
'This code will highlight words that do not belong in the paragraph
WordList = Split(" is , are ,", ",") 'List of words to check for when it is peer-reviewing
Options.DefaultHighlightColorIndex = wdPink *'Highlight when found*
For a = 0 To UBound(WordList())
Set r = ActiveDocument.Range
With r.Find
.Text = WordList(a)
.Replacement.Highlight = wdYellow
.Execute Replace:=wdReplaceAll
End With
Next 'next word
ShortCut:
Next
End Sub

Here are three ways to retrieve an array of words from an external file (Word, Excel, and Text Files) in MS Word. Reading from the text file is by far the fastest.
Results
Word: 0.328125 Seconds
Excel: 1.359130859375 Seconds
Text: 0.008056640625 Seconds
---------- ----------
Get Word List from Word Document
Start Time:12/1/2007 11:03:56 PM
End Time:9/1/2016 12:53:16 AM
Duration:0.328125 Seconds
------------------------------
---------- ----------
Get Word List from Excel
Start Time:12/1/2007 3:05:49 PM
End Time:9/1/2016 12:53:17 AM
Duration:1.359130859375 Seconds
------------------------------
---------- ----------
Get Word List from Text Document
Start Time:11/30/2007 6:16:01 AM
End Time:9/1/2016 12:53:17 AM
Duration:0.008056640625 Seconds
------------------------------
Unit Test
Sub TestWordList()
Dim arData
EventsTimer "Get Word List from Word Document"
arData = GetWordsListDoc
'Debug.Print Join(arData, ",")
EventsTimer "Get Word List from Word Document"
EventsTimer "Get Word List from Excel"
arData = GetWordsListXL
'Debug.Print Join(arData, ",")
EventsTimer "Get Word List from Excel"
EventsTimer "Get Word List from Text Document"
arData = GetWordsListTxt
'Debug.Print Join(arData, ",")
EventsTimer "Get Word List from Text Document"
End Sub
Event Timer
Sub EventsTimer(Optional EventName As String)
Static dict As Object
If dict Is Nothing Then Set dict = CreateObject("Scripting.Dictionary")
If dict.Exists(EventName) Then
Debug.Print
Debug.Print String(10, "-"), String(10, "-")
Debug.Print EventName
Debug.Print ; "Start Time:"; ; Now - dict(EventName)
Debug.Print ; "End Time:"; ; Now
Debug.Print ; "Duration:"; ; Timer - dict(EventName) & " Seconds"
Debug.Print String(10, "-"); String(10, "-"); String(10, "-")
dict.Remove EventName
Else
dict.Add EventName, CDbl(Timer)
End If
If dict.Count = 0 Then Set dict = Nothing
End Sub
Functions to retrieve a word list from MS Word, Ms Excel and a Text File.
Function GetWordsListDoc()
Const FilePath As String = "C:\Users\best buy\Downloads\stackoverfow\Wordlist\WordList.docx"
Dim doc As Word.Document, oWords As Word.Words
Dim x As Long
Dim arData
Set doc = Application.Documents.Open(FileName:=FilePath, ReadOnly:=True)
Set oWords = doc.Words
ReDim arData(oWords.Count - 1)
For x = 1 To oWords.Count
arData(x - 1) = Trim(oWords.Item(x))
Next
doc.Close False
GetWordsListDoc = arData
End Function
Function GetWordsListXL()
Const FilePath As String = "C:\Users\best buy\Downloads\stackoverfow\Wordlist\WordsList.xlsb"
Const xlUp = -4162
Dim arData
Dim x As Long
Dim oExcel As Object, oWorkbook As Object
Set oExcel = CreateObject("Excel.Application")
With oExcel
.Visible = False
Set oWorkbook = .Workbooks.Open(FileName:=FilePath, ReadOnly:=True)
End With
With oWorkbook.Worksheets(1)
arData = .Range("A1", .Range("A" & .Rows.Count).End(xlUp)).Value
arData = oExcel.WorksheetFunction.Transpose(arData)
End With
oWorkbook.Close False
oExcel.Quit
GetWordsListXL = arData
End Function
Function GetWordsListTxt()
Const FilePath As String = "C:\Users\best buy\Downloads\stackoverfow\Wordlist\WordList.txt"
Dim arData, f, fso
Set fso = CreateObject("Scripting.Filesystemobject")
Set f = fso.OpenTextFile(FilePath)
arData = Split(f.ReadAll, vbNewLine)
GetWordsListTxt = arData
End Function

Related

Error 4608 : value out of range error in MS Word VBA (only in word 2007)

We have a macro in our word document which exports a PDF for each record in Mail Merge. When creating the doc, word always added a blank page to it, so we had to find a way to delete the last page (blank one). We added the .Range(Lr - 1, TargetDoc.Range.End).Delete line, and it worked perfectly; but only in Word > 2007 - when we tried running the macro in Word 2007, it said :
Option Explicit
Const FOLDER_SAVED As String = "F:\Postcard\" '//Makes sure your folder path ends with a backward slash
Const SOURCE_FILE_PATH As String = "G:\Laptop Data\GoaRegion.xlsm"
Sub TestRun()
Dim MainDoc As Document, TargetDoc As Document
Dim dbPath As String
Dim recordNumber As Long, totalRecord As Long
Dim Lr As Long
Set MainDoc = ActiveDocument
With MainDoc.MailMerge
'// if you want to specify your data, insert a WHERE clause in the SQL statement
.OpenDataSource Name:=SOURCE_FILE_PATH, sqlstatement:="SELECT * FROM [Goa$]"
totalRecord = .DataSource.RecordCount
For recordNumber = 1 To totalRecord
With .DataSource
.ActiveRecord = recordNumber
.FirstRecord = recordNumber
.LastRecord = recordNumber
End With
.Destination = wdSendToNewDocument
.Execute False
Set TargetDoc = ActiveDocument
With TargetDoc
Lr = .GoTo(wdGoToPage, wdGoToLast).Start
.Range(Lr - 1, TargetDoc.Range.End).Delete
End With
TargetDoc.ExportAsFixedFormat FOLDER_SAVED & .DataSource.DataFields("Voter").Value & ".pdf", exportformat:=wdExportFormatPDF
TargetDoc.Close False
Set TargetDoc = Nothing
Next recordNumber
End With
Set MainDoc = Nothing
End Sub
Is there something wrong? Does Word 2007 not support the line .Range(Lr - 1, TargetDoc.Range.End).Delete? Kindly guide... Thanks!
Try this:
If Not Application.Version = "12.0" Then
With TargetDoc
Lr = .GoTo(wdGoToPage, wdGoToLast).Start
.Range(Lr - 1, TargetDoc.Range.End).Delete
End With
End If

Why does the .Find function appear to not work properly in this code?

The program is supposed to loop through a directory to find every occurrence of a word from a list that is in another word document and expand selection to the whole question. This program is supposed to allow you to compile a list of test questions from a test bank based on a list of highly relevant key terms. Eventually, once all the relevant questions are selected They would be copied to a new document.
Sub CompareWordList()
'program to loop through Directory to find every occurrence of a word from a list and expand selection to
'the whole question. This program is supposed to allow you to compile a list of test questions from a
'test bank based on a list of highly relevent key terms. Eventually, once all the relevent questions are selected
'They would be copied to a new document
'variables for directory looping
Dim vDirectory As String
Dim oDoc As Document
'generates file path
vDirectory = "D:\school\documents\MGT450\Test_Bank\TB - test\" 'set directory to loop through
vFile = Dir(vDirectory & "*.*") 'file name
'variables for selection
Dim sCheckDoc As String
Dim docRef As Document
'Dim docCurrent As Document
Dim wrdRef As Object
'list of words to look for
sCheckDoc = "D:\testlist.docx"
Set docRef = Documents.Open(sCheckDoc)
'docCurrent.Activate
docRef.Activate
'Directory Loop
Do While vFile <> ""
Set oDoc = Documents.Open(FileName:=vDirectory & vFile)
'document activation
oDoc.Activate
SendDocToArray_FindWords (sCheckDoc)
'Havent really worked on this area yet, as been focused on find issue
docRef.Close
'close document modification
oDoc.Close SaveChanges:=False
vFile = Dir
Loop
End Sub
'After every instance of a particular phrase is selected, select question
around said phrase
Function SelectQuestion(Index As Long)
'iniitial declaration
Dim linecount As Integer
Set mydoc = ActiveDocument
Dim oPara As word.Paragraph
'Dim oPara As selection
Dim ListLevelNumber As Integer
Dim holder As Long
'if list type is simple numbering
If selection.Range.ListFormat.ListType = wdListSimpleNumbering Or
wdListBullet Or wdListMixedNumbering Then
'Select Whole Question containing word
With selection
.StartIsActive = False
.Extend Character:=";"
.EndKey
.StartOf (wdLine)
End With
a = selection.MoveUntil(";", wdBackward)
b = selection.MoveDown(wdLine, 2, wdMove)
selection.StartOf (wdLine)
selection.Find.Execute "*^13^13", , , True
'some correction of range- remove last paragraph from selection
ActiveDocument.Range(selection.Start, selection.End - 1).Select
End If
End Function
Function GetParNum(r As Range) As Integer
'determines paragraph number
GetParNum = selection.Range.ListFormat.ListValue
End Function
Sub Test() 'testing function
CountWords
End Sub
Function SendDocToArray_FindWords(name As String) As Variant
'sends a document to an array split by newline
'the document that is send to the array is composed of the words that are
'being searched for.
Dim doc As Document
Set doc = Documents.Open(name)
Dim arr() As String
arr() = Split(doc.Content.Text, Chr(13))
Dim iCount As Integer
Dim targetRng As Range
For Each i In arr()
Dim r As Range
Dim j As Long
Set r = ActiveDocument.Content
With r.Find
'If I pass a variable to FindText it only finds the first instance of the word then
'prematurely exits loop or becomes an infinite loop
'strangely the function is only working when I hardcode the word such as
'FindText:= "International Business"
Do While .Execute(FindText:=i, Forward:=True, Wrap:=wdFindContinue) = True
If r.Find.Found = True Then
j = j + 1
End If
Loop
End With
MsgBox "The Word" & i & " was found " & j & " times."
Next i
MsgBox ("Finished Selecting")
End Function
'testing count words function
Function CountWords(c As String) 'ByRef word As Variant
'counts number of occurences of words in document
Dim r As Range
Dim j As Long
Set r = ActiveDocument.Content
'ResetFRParameters r
With r.Find
'.Wrap = wdFindContinue
Do While .Execute(FindText:=i, Forward:=True) = True
If r.Find.Found = True Then
j = j + 1
End If
Loop
End With
MsgBox "Given word(s) was found " & j & " times."
End Function
'testing count words function
Sub FindText()
Dim MyAR() As String
Dim i As Long
i = 0
selection.HomeKey Unit:=wdStory
selection.Find.Text = "International Business"
' selection.Range.Text
Do While selection.Find.Execute = True
ReDim Preserve MyAR(i)
MyAR(i) = selection
i = i + 1
Loop
If i = 0 Then
MsgBox "No Matches Found"
Exit Sub
End If
For i = LBound(MyAR) To UBound(MyAR)
MsgBox ("# of International Business occurrences " & i)
Next i
End Sub
I used three finds that I was trying to get to work correctly but they do not appear to search the whole document regardless how I use them. I have started wondering if the formatting of my document is to blame. I have attached both an image of the list of terms as well as document to search through.
This is the list of terms to search through
This is the document to search through
My ultimate question is how do I get around this problem and find all instances of the given search term in the document? As of now it either finds the first instance and breaks or becomes an infinite loop.
This is the final that works, although not he prettiest, for others who may be looking for similar code: (pasting it here as messed up the format a bit so youll need to fix those if you use it)
Sub TraversePath()
Dim fso As Object 'FileSystemObject
Dim fldStart As Object 'Folder
Dim fld As Object 'Folder
Dim fl As Object 'File
Dim Mask As String '.doc,.docx,.xlsx, etc
Set fso = CreateObject("scripting.FileSystemObject") ' late binding
'Set fso = New FileSystemObject 'or use early binding (also replace Object
types)
Set fldStart = fso.GetFolder("D:\school\documents\MGT450\Test_Bank\TB -
test\") ' Base Directory
Mask = "*.doc"
ListFiles fldStart, Mask
'for each file in folder
'For Each fl In fldStart
' ListFiles fld, Mask
MsgBox ("Fin.")
'Next
End Sub
Sub ListFiles(fld As Object, Mask As String)
Dim runTracker As Integer
runTracker = 0
Dim fl As Object 'File
x = NewDoc 'generate new processed study guide
Dim sCheckDoc As String
Dim docRef As Document
Dim vFile As String
Dim arr() As String
'list of words to look for
sCheckDoc = "D:\testlist.docx"
Set docRef = Documents.Open(sCheckDoc)
docRef.Activate
'send docref to array split by newline
arr() = Split(docRef.Content.Text, Chr(13))
'begin word array loop?
For Each fl In fld.Files
runTracker = runTracker + 1
If fl.name Like Mask Then
'-----------------------------------------------------------------run
program code
vFile = fl.name 'set vFile = current file name
a = Documents.Open(fld.path & "\" & fl.name) 'open current search
file
Documents(vFile).Activate 'activate current search file
For a = 0 To UBound(arr)
'reset selection
selection.HomeKey Unit:=wdStory, Extend:=wdMove
'Inform progress
StatusBar = "Running Find..."
Dim docB As String
docB = Documents("Processed_StudyGuide.docx")
Dim docA As String
docA = Documents(vFile)
Documents(docA).Activate
b = DoFindReplace_Bkmk(arr(a))
'print bookmarked values to new document
StatusBar = "Printing targeted paragraphs..."
PrintBookmarks (bookmarkName)
If b <> 0 Then
'notify how many were inserted
MsgBox ("Complete, inserted: " & b & " bookmarks of " &
arr(a))
End If
Next a
MsgBox ("finished find in: " & vFile)
Documents(vFile).Close (wdDoNotSaveChanges)
'-----------------------------------------------------------------end
code
End If
Next
MsgBox ("Finished all documents")
End Sub
Function SelectQuestion(Index As Long)
'iniitial declaration
Dim linecount As Integer
Dim oPara As word.Paragraph
'Dim oPara As selection
Dim ListLevelNumber As Integer
Dim holder As Long
'if list type is simple numbering
If selection.Range.ListFormat.ListType = wdListSimpleNumbering Or
wdListBullet Or wdListMixedNumbering Then
'Select Whole Question containing word
With selection
.StartIsActive = False
.Extend Character:=";"
.EndKey
.StartOf (wdLine)
End With
a = selection.MoveUntil(";", wdBackward)
b = selection.MoveDown(wdLine, 2, wdMove)
selection.StartOf (wdLine)
selection.Find.Execute "*^13^13", , , True
'some correction of range- remove last paragraph from selection
'ActiveDocument.Range(selection.start, selection.End - 1).Select
End If
End Function
Function GetParNum(r As Range) As Integer
'determines paragraph number
GetParNum = selection.Range.ListFormat.ListValue
End Function
Function NewDoc() As String
'Generate new document and save
a = Documents.Add(, , , True)
ActiveDocument.Content.Delete
ActiveDocument.SaveAs2 ("D:\Processed_StudyGuide")
End Function
Public Function GetName(num As Integer) As String
'names each bookmark
Dim t As String
Dim nameArr() As Variant
nameArr = Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "aa",
"bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk", "ll", "mm",
"nn", "oo", "pp", "qq", "rr", "ss", "tt", "uu", "vv", "ww", "xx", "yy",
"zz", "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj",
"kkk", "lll", "mmm", "nnn", "ooo", "ppp", "qqq", "rrr", "sss", "ttt", "uuu",
"vvv", "www", "xxx", "yyy", "zzz", "aaaa", "bbbb", "cccc", "dddd", "eeee",
"ffff", "gggg", "hhhh", "iiii", "jjjj", "kkkk", "llll", "mmmm", "nnnn",
"oooo", "pppp", "qqqq", "rrrr", "ssss", "tttt", "uuuu", "vvvv", "wwww",
"xxxx", "yyyy", "zzzz", "aaaaa", "bbbbb", "ccccc", "ddddd")
t = nameArr(num)
GetName = t
End Function
Function PrintBookmarks(name As String) 'Add each selection to collection
'Declarations
selection.Collapse
Dim n As Integer
Dim docB As String
docB = Documents("Processed_StudyGuide.docx")
Dim docA As String
docA = ActiveDocument.name
Dim x As Integer
x = ActiveDocument.Bookmarks.Count
Dim a As String
For Each bkmark In Documents(docA).Bookmarks
'If # of bookmarks is greater than 0 select the one at x
If x > 0 Then
With ActiveDocument.Bookmarks(x)
BkMkName = .name
.Select
End With
End If
'selection.Bookmarks(a).Select
SelectQuestion (GetParNum(selection.Range))
selection.Copy
selection.Collapse (wdCollapseEnd)
Documents("Processed_StudyGuide.docx").Activate
selection.MoveEnd
selection.Paste
'reactivate last document
Documents(docA).Activate
x = x - 1
Next
'runs bookmark removal
removebookmarks (docA)
Documents(docB).Activate 'activate processed study guide
' If ActiveDocument.Bookmarks.Count > 0 Then
' FixRepeatedQuestions
' End If
removebookmarks (docB)
ActiveDocument.Save
Documents(docA).Activate
End Function
Sub removebookmarks(name As String)
'removes bookmarks from documents
Dim bkm As Bookmark
For Each bkm In ActiveDocument.Bookmarks
bkm.Delete
Next bkm
End Sub
Function DoFindReplace_Bkmk(ByRef FindText As Variant, Optional ReplaceText
As String) As Integer
Dim i As Integer
i = 0
Dim bkmark As String
With selection.Find
'set Find Parameters
.ClearFormatting
.Replacement.ClearFormatting
.Text = FindText
'If replacement text is not supplied replace with targetword to find
If ReplaceText = "" Then
.Replacement.Text = FindText
Else
.Replacement.Text = ReplaceText
End If
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute
'Keep going until nothing found
.Execute Replace:=wdReplaceAll
'keep track of how many are replaced
'get bookmark name and add bookmark at location
bookmarkName = GetName(i)
ActiveDocument.Bookmarks.Add name:=bookmarkName, Range:=selection.Range
i = i + 1 'below because array starts at 0
Loop
'Free up some memory
ActiveDocument.UndoClear
End With
'return # of find/replacements
DoFindReplace_Bkmk = i
End Function
For Each i In arr() can't work.
Your Arr() is a string and the Each enumeration only works for objects. You would have to use
For i = 0 to Ubound(Arr)
Next i
Here is the complete code for repetitive searching. Note that the TestCount function prints its output to VBE's Immediate window. If you don't see it, press Ctl+G or select it from the View menu, or change the output to a MsgBox.
Sub TestCount()
' testing procedure
Dim MyPhrase As String
MyPhrase = "International business"
Debug.Print "My phrase was found " & CountWords(MyPhrase) & " times."
End Sub
Function CountWords(Phrase As String) As Integer
' 12 Apr 2017
' return the number of occurences of words in document
Dim Fun As Integer ' Function return value
Dim Rng As Range
Set Rng = ActiveDocument.Content
Do
With Rng.Find
.ClearFormatting
.MatchCase = False
.Text = Phrase
.Execute
If Not .Found Then Exit Do
Fun = Fun + 1
End With
Loop
CountWords = Fun
End Function
For your understanding:-
Find always starts the search at the beginning of the range you set. At the start of the procedure the range is defined as ActiveDocument.Content.
When a match is found, the range is reset to hold only the found phrase, meaning Rng isn't the same as it was before.
The loop now repeats the search with the changed Rng object, again starting at the beginning of that range to the end of the document.
When no more match is found the loop is exited. It's important, not to Wrap because that property instructs Find to continue looking for matches at the beginning of the document when no match is found before its end.
In between, in the place where you now see Fun = Fun + 1, you could execute any code you like - perhaps call a sub there which makes major changes or even copies parts of the document to another document. The important thing is that, after you come back from all that work, the Rng pointer still holds that part of the document from where you want to continue your search.
O hope this will speed you on your way.

Find all Heading 1 Text and Put it into an Array

I am using a VBA Macro to render all the "Heading 1" style text from a word document.
It is working fine but taking huge time depends on the content of word doc.
I am looping each paragraph to check for "Heading 1" style and render the Text into an array.
I wonder if there is an alternative approach to simply find "Heading 1" style and store the text in array which would greatly reduce the execution time.
Below my Macro program and I would appreciate any expert thoughts regarding the above mentioned.
Sub ImportWordHeadings()
Dim wdDoc As Object
Dim wdFileName As Variant
Dim sHeader(50) As String
Dim Head1counter As Integer
Dim arrcount As Long
Dim mHeading As String
On Error Resume Next
wdFileName = Application.GetOpenFilename("Word files (*.doc),*.doc", , _
"Browse for file containing table to be imported")
If wdFileName = False Then Exit Sub '(user cancelled import file browser)
Set wdDoc = GetObject(wdFileName) 'open Word file
p = 1
RetCount = 0
parg = wdDoc.Paragraphs.Count
For Head1counter = 1 To parg
If wdDoc.Paragraphs(Head1counter).Range.Style = "Heading 1" Then
sHeader(p) = wdDoc.Paragraphs(Head1counter).Range.Text
p = p + 1
Else
p = p
End If
Next Head1counter
For arrcount = RetCount + 1 To UBound(sHeader)
If sHeader(arrcount) <> "" Then
Debug.Print sHeader(arrcount)
RetCount = arrcount
Exit For
Else
RetCount = RetCount
End If
Next arrcount
Set wdDoc = Nothing
End Sub
You can use the Find method to search for all of the headings, very similar to what I did over here on Code Review.
Set doc = ActiveDocument
Set currentRange = doc.Range 'start with the whole doc as the current range
With currentRange.Find
.Forward = True 'move forward only
.Style = wdStyleHeading1 'the type of style to find
.Execute 'update currentRange to the first found instance
dim p as long
p = 0
Do While .Found
sHeader(p) = currentRange.Text
' update currentRange to next found instance
.Execute
p = p + 1
Loop
End With

VBA issue with operators

I am facin strange problem looks like = is not working as it should be. I got code below:
Dim lineText As String
For Each p In WordDoc.Paragraphs
lineText = p.Range.Text
If lineText = "" Then GoTo Dalej
.....
even if i do:
lineText = ""
If lineText = "" Then GoTo Dalej
its not going to Dalej but going next. Looks like its not problem with code but with operators i got similar problem with <>. I tried to workaround tht with InStr or StrComp but its doing completly not as it should be like something inside excel has been changed with application itself. Do you have any idea what this could be?
This is full code:
Sub Sprawdz_Pola_Korespondencji_Click()
Application.ScreenUpdating = True
Dim RowNr As Integer
Dim EWS As Worksheet
RowNr = 30
Set EWS = Sheets("Arkusz do wypełnienia")
Dim FileName As Variant, wb As Workbook
FileName = Application.GetOpenFilename(FileFilter:="Word File (*.docx),*.docx", Title:="Select File To Be Opened")
If FileName = False Then Exit Sub
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = False
Set WordDoc = WordApp.Documents.Open(FileName)
Dim p As Paragraph
If lineText = "" Then GoTo Dalej
If InStr(lineText, PoleExcel) Then
EWS.Cells(5, X).Interior.ColorIndex = 18
Else
EWS.Cells(5, X).Interior.ColorIndex = 3
End If
Dalej:
Next p
Nastepna:
Loop Until EWS.Cells(RowNr, X) = "KONIEC"
'EWS.Activate 'WordDoc.Activate '<============================================================
WordDoc.Close savechanges:=False 'or false
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub
Public Function ReplaceSpaces(strInput As String) As String
' Replaces spaces in a string of text with underscores
Dim Result As String
Result = strInput
If InStr(strInput, " ") > 0 Then
Result = Replace(strInput, " ", "_")
End If
ReplaceSpaces = Result
End Function
You need to write:
Next p
Dalej:
instead. (i.e. switch round the Next p and Dalej:). Currently the label is inside the for loop.
But, it would be far better to use Exit For instead of the GoTo. Doing this means you don't need to maintain a label.
GoTo statements are notoriously brittle.
To strip out the CR do this:
lineText = replace(lineText, chr(13), "")

word macro split file on delimeter

I have multiple large docx files (word 2010) which need to be split on basis of a delimiter ("///"). I tried using a macro given http://www.vbaexpress.com/forum/showthread.php?39733-Word-File-splitting-Macro-question
However it gives an error "This method or Property is not available since No Text is Selected" on the line colNotes(i).Copy (Sub SplitNotes(...)).
The macro is reproduced below:
Sub testFileSplit()
Call SplitNotes("///", "C:\Users\myPath\temp_DEL_008_000.docx")
End Sub
Sub SplitNotes(strDelim As String, strFilename As String)
Dim docNew As Document
Dim i As Long
Dim colNotes As Collection
Dim temp As Range
'get the collection of ranges
Set colNotes = fGetCollectionOfRanges(ActiveDocument, strDelim)
'see if the user wants to proceed
If MsgBox("This will split the document into " & _
colNotes.Count & _
" sections. Do you wish to proceed?", vbYesNo) = vbNo Then
Exit Sub
End If
'go through the collection of ranges
For i = 1 To colNotes.Count
'create a new document
Set docNew = Documents.Add
'copy our range
colNotes(i).Copy
'paste it in
docNew.Content.Paste
'save it
docNew.SaveAs fileName:=ThisDocument.path & "\" & strFilename & Format(i, "000"), FileFormat:=wdFormatDocument
docNew.Close
Next
End Sub
Function fGetCollectionOfRanges(oDoc As Document, strDelim As String) As Collection
Dim colReturn As Collection
Dim rngSearch As Range
Dim rngFound As Range
'initialize a new collection
Set colReturn = New Collection
'initialize our starting ranges
Set rngSearch = oDoc.Content
Set rngFound = rngSearch.Duplicate
'start our loop
Do
'search through
With rngSearch.Find
.Text = strDelim
.Execute
'if we found it... prepare to add to our collection
If .Found Then
'redefine our rngfound
rngFound.End = rngSearch.Start
'add it to our collection
colReturn.Add rngFound.Duplicate
'reset our search and found for the next
rngSearch.Collapse wdCollapseEnd
rngFound.Start = rngSearch.Start
rngSearch.End = oDoc.Content.End
Else
'if we didn't find, exit our loop
Exit Do
End If
End With
'shouldn't ever hit this... unless the delimter passed in is a VBCR
Loop Until rngSearch.Start >= ActiveDocument.Content.End
'and return our collection
Set fGetCollectionOfRanges = colReturn
End Function
For those who might be interested:
The code does work in 2010. The issue was a delimiter which was the first thing on the file...
Deleted it and it worked...