Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Erasing whole line via VBScript doesn't work

Posted on 2014-02-26
9
Medium Priority
?
750 Views
Last Modified: 2014-03-04
Hi,

I'm trying to erase a line of text, including the end-of-paragraph mark. When I manually do it in Word, it works fine - in vbscript, it doesn't. It enters the .Execute statement and each line w/o error. But nothing happens to the text.

In the debugger, the find and replace variables look fine.
strFindText = "erase this paragraph^p"
strReplacementText = ""


Any ideas?

I'm running the script in XP SP3.

Const TIMEOUT_1_SEC = 1
Const POPUP_TITLE = "Find and Replace"

Dim objShell 'As IWshRuntimeLibrary.WshShell
Dim objDoc 'As Word.Document
Dim objWord 'As Word.Application
Dim objRangeFind 'As Word.Find

Set objShell = CreateObject("WScript.Shell")

Sub FindNRepl
	sFilename = "C:\Local\test2.doc"
	
	Set objDoc = objWord.Documents.Open(sFilename)
	strFindText = "erase this paragraph^p"
	strReplacementText = ""
	Do While Not IsEmpty(strFindText)
		Set objRangeFind = objDoc.Range.Find
		objRangeFind.ClearFormatting
		objRangeFind.Replacement.ClearFormatting
		With objRangeFind
			.Text = strFindText
			.Replacement.Text = strReplacementText
			.Forward = True
			.Wrap = wdFindContinue
			.Format = False
			.MatchCase = True
			.MatchWholeWord = False
			.MatchWildcards = False
			.MatchSoundsLike = False
			.MatchAllWordForms = False
			.Replacement.Font.Color = vbMagenta
			If .Execute Then
				objShell.Popup "Replacing text...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
				objRangeFind.Execute, , , , , , , , , ,wdReplaceAll
				objShell.Popup "Replacement done.", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
				If objDoc.Saved = False Then
					objDoc.Save
				End If
			Else
				objShell.Popup "Not found...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
			End If
		End With
		' Get next find and replace strings
		'nRecFind = nRecFind + 1
		'strFindText = aStrs(nRecFind,0)
		'strReplacementText = aStrs(nRecFind,1)
	Loop 'While Not IsEmpty(strFindText)
End Sub

Open in new window



Chris
0
Comment
Question by:NVIT
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
9 Comments
 
LVL 57

Assisted Solution

by:Bill Prew
Bill Prew earned 400 total points
ID: 39890161
Is this the entire script?  If so then there are some problems before I even get to the replace logic.  The subroutine is not called.  And in the subroutine you reference objWord, but that variable is never set to an object...

~bp
0
 
LVL 76

Assisted Solution

by:GrahamSkan
GrahamSkan earned 1600 total points
ID: 39890163
There is a lot of extra unnecessary code here, and it is hard to understand how the loop is ever to end, since strFindText is does not get changed.
I would start with this:
Sub FindNRep2()
    sFilename = "C:\Local\test2.doc"
    
    Set objDoc = objWord.Documents.Open(sFilename)
    strFindText = "erase this paragraph^p"
    strReplacementText = ""
    
    With objDoc.Range.Find
        .Text = strFindText
        .Replacement.Text = strReplacementText
        If .Execute Then
            objShell.Popup "Replacing text...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
            objRangeFind.Execute , , , , , , , , , , wdReplaceAll
            objShell.Popup "Replacement done.", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
            If objDoc.Saved = False Then
                objDoc.Save
            End If
        Else
            objShell.Popup "Not found...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
        End If
    End With
End Sub

Open in new window

0
 
LVL 25

Author Comment

by:NVIT
ID: 39890245
Sorry, all. Here's a code repost.

BTW, how can I see the result of the "objRangeFind.Execute, , , , , , , , , ,wdReplaceAll" line?

Const TIMEOUT_1_SEC = 1
Const POPUP_TITLE = "Find and Replace"

Dim objShell 'As IWshRuntimeLibrary.WshShell
Dim objDoc 'As Word.Document
Dim objWord 'As Word.Application
Dim objRangeFind 'As Word.Find

Set objShell = CreateObject("WScript.Shell")

FindNRepl

Sub FindNRepl
	sFilename = "C:\Local\test2.doc"
	Set objWord = CreateObject("Word.Application")
	objWord.Visible = True 'make sure that you can see instances of Application
	Set objDoc = objWord.Documents.Open(sFilename)
	strFindText = "erase this paragraph^p"
	strReplacementText = ""
	Do While Not IsEmpty(strFindText)
		Set objRangeFind = objDoc.Range.Find
		objRangeFind.ClearFormatting
		objRangeFind.Replacement.ClearFormatting
		With objRangeFind
			.Text = strFindText
			.Replacement.Text = strReplacementText
			If .Execute Then
				objShell.Popup "Replacing text...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
				objRangeFind.Execute, , , , , , , , , ,wdReplaceAll
				objShell.Popup "Replacement done.", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
				If objDoc.Saved = False Then
					objDoc.Save
				End If
			Else
				objShell.Popup "Not found...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
			End If
		End With
		strFindText = emptyvar
	Loop 'While Not IsEmpty(strFindText)
	CloseWordAppAndQuit
End Sub

'-------------------------------------------------------------------------------
' CloseWordAppAndQuit
'-------------------------------------------------------------------------------
sub CloseWordAppAndQuit
	objWord.NormalTemplate.Saved = True 'so the dialog doesn't ask if we want to save the NORMAL.DOT template.
	objWord.Quit
	WScript.Quit
end sub

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 76

Expert Comment

by:GrahamSkan
ID: 39890321
Not too sure where you are stuck, but here is an (untested) suggestion.
After a successful find, the input Range object is set to the the found range, so here you can simply delete the first paragraph. Note that I use the VBA editor to create this, so I might have left some VBA-only syntax.
'Sub FR()
Const TIMEOUT_1_SEC = 1
Const POPUP_TITLE = "Find and Replace"

Dim objShell 'As IWshRuntimeLibrary.WshShell
Dim objDoc 'As Word.Document
Dim objWord 'As Word.Application
Dim objRangeFind 'As Word.Find
Dim rng          ' As Range

Set objShell = CreateObject("WScript.Shell")

FindNRepl

Sub FindNRepl()
    sFilename = "C:\Local\test2.doc"
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True 'make sure that you can see instances of Application
    Set objDoc = objWord.Documents.Open(sFilename)
    strFindText = "erase this paragraph^p"
    strReplacementText = ""
    Do While Not IsEmpty(strFindText)
        Set rng = objDoc.Range
        Set objRangeFind = rng.Find
        With objRangeFind
            .Text = strFindText
            .Replacement.Text = strReplacementText
            If .Execute Then
                rng.Paragraphs.First.Delete
                objShell.Popup "Replacing text...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
                objRangeFind.Execute , , , , , , , , , , wdReplaceAll
                objShell.Popup "Replacement done.", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
                If objDoc.Saved = False Then
                    objDoc.Save
                End If
            Else
                objShell.Popup "Not found...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
            End If
        End With
        strFindText = emptyvar
    Loop 'While Not IsEmpty(strFindText)
    CloseWordAppAndQuit
'End Sub

Open in new window

0
 
LVL 25

Author Comment

by:NVIT
ID: 39890367
Hi Graham,

I haven't tried your solution yet.

Mine is basically a find and replace tool which works fine until now I have to erase the entire line, i.e. paragraph. Some documents have single-line text such as titles. If I just use "erase this paragraph", it leaves the blank line. So, I added the ^p at the end. It works fine manually in Word but not in this macro.

Again, I haven't had a chance to try your solution yet. At face value, it seems to ALWAYS delete the text. Would it still work with general find and replace?
0
 
LVL 25

Author Comment

by:NVIT
ID: 39890715
In the Find dialog, I enter: erase this paragraph^p
In the Replace dialog, I enter: ^p

This results in a blank line, as expected.

Rewind and try this...

In the Find dialog, I enter: erase this paragraph^p
In the Replace dialog, I don't enter any text. Just pick OK.

It doesn't erase the text and ^p mark, as I'd expect. As I said in my OP, it enters the statement but nothing happens.

Rewind and try this...

In the Find dialog, I enter: erase this paragraph^p
In the Replace dialog, I enter a single SPACE character.

This results erasing the line and ^p mark. But, the next line is now prefixed with a space character. Although it's not obvious to the eye, this is not the proper way to do it.

Any suggestions?
0
 
LVL 76

Assisted Solution

by:GrahamSkan
GrahamSkan earned 1600 total points
ID: 39891899
Here is a tested VBScript:
'Sub FR()
Const TIMEOUT_1_SEC = 1
Const POPUP_TITLE = "Find and Replace"

Dim objShell 'As IWshRuntimeLibrary.WshShell
Dim objDoc 'As Word.Document
Dim objWord 'As Word.Application
Dim objRangeFind 'As Word.Find
Dim rng          ' As Range

Set objShell = CreateObject("WScript.Shell")

FindNRepl

Sub FindNRepl()
    sFilename = "C:\Local\test2.doc"
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True 'make sure that you can see instances of Application
    Set objDoc = objWord.Documents.Open(sFilename)
    strFindText = "erase this paragraph^p"
    strReplacementText = ""
    Do While Not IsEmpty(strFindText)
        Set rng = objDoc.Range
         With rng.Find
            .Text = strFindText
            .Replacement.Text = strReplacementText
            If .Execute Then
                rng.Paragraphs.First.Range.Delete
                'objShell.Popup "Replacing text...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
                'objRangeFind.Execute , , , , , , , , , , wdReplaceAll
                'objShell.Popup "Replacement done.", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
                If objDoc.Saved = False Then
                    objDoc.Save
                End If
            Else
                objShell.Popup "Not found...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
            End If
        End With
        strFindText = emptyvar
    Loop 'While Not IsEmpty(strFindText)
    CloseWordAppAndQuit
End Sub

'-------------------------------------------------------------------------------
' CloseWordAppAndQuit
'-------------------------------------------------------------------------------
sub CloseWordAppAndQuit
	objWord.NormalTemplate.Saved = True 'so the dialog doesn't ask if we want to save the NORMAL.DOT 

template.
	objWord.Quit
	WScript.Quit
end sub     

Open in new window

0
 
LVL 25

Accepted Solution

by:
NVIT earned 0 total points
ID: 39893212
Here's the final code. It now lets me replace or delete text. In the end, I didn't use your "rng.Paragraphs.First.Range.Delete". Instead, it was a matter of knowing more how the Find object works. Still, since you guys helped me get there, I'll split the points:

Const wdReplaceAll = 2
Const POPUP_TITLE = "Find and Replace"
Const TIMEOUT_1_SEC = 1

Dim objShell 'As IWshRuntimeLibrary.WshShell
Dim objDoc 'As Word.Document
Dim objWord 'As Word.Application
Dim objRangeFind 'As Word.Find

Set objShell = CreateObject("WScript.Shell")

FindNRepl

Sub FindNRepl()
	sFilename = "c:\local\FindNRepl.doc"
	Set objWord = CreateObject("Word.Application")
	objWord.Visible = True 'make sure that you can see instances of Application
	Set objDoc = objWord.Documents.Open(sFilename)
	strFindText = "Erase this paragraph^p"
	strReplacementText = ""
	Do While Not IsEmpty(strFindText)
    Set rng = objDoc.Range
    With rng.Find
			.Text = strFindText
			.Replacement.Text = strReplacementText
      .Wrap = wdFindContinue
			If strReplacementText <> "" Then
				objShell.Popup "Replacing text...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
				.Execute , , , , , , , , , , wdReplaceAll
			Else
				objShell.Popup "Erasing text...", TIMEOUT_1_SEC, POPUP_TITLE, vbInformation + vbOKOnly
				.Execute , , , , , , , , , , wdReplaceAll
			End If
			If objDoc.Saved = False Then
				objDoc.Save
			End If
		End With
		strFindText = emptyvar
	Loop 'While Not IsEmpty(strFindText)
	CloseWordAppAndQuit
End Sub

'-------------------------------------------------------------------------------
' CloseWordAppAndQuit
'-------------------------------------------------------------------------------
sub CloseWordAppAndQuit
	objWord.NormalTemplate.Saved = True 'so the dialog doesn't ask if we want to save the NORMAL.DOT template.
	objWord.Quit
	WScript.Quit
end sub

Open in new window

0
 
LVL 25

Author Closing Comment

by:NVIT
ID: 39902811
Here's the final code. It now lets me replace or delete text. In the end, I didn't use Graham's "rng.Paragraphs.First.Range.Delete". Instead, it was a matter of knowing more how the Find object works and revising accordingly.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A few years ago I was very much a beginner at VBA, and that very much remains the case today.  I'll do my best to explain things as I go in the hope that other beginners can follow.  If you just want to check out a tool that creates a Select Case fu…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This video shows and describes the main difference between both orientations in Microsoft Word. Viewers will understand when to use each orientation and how to get the most out of them.
This video walks the viewer through the process of creating Hyperlinks for the web and other documents. Select the "Insert" tab: Click "Hyperlink":  Type "http://" followed by a web address to reference a website or navigate to a document to ref…
Suggested Courses

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question