Deleting everything between two given characters

J

John Doue

Hi,

I came across a very simple problem for which my limited knowledge found
no solution.

I need a macro that deletes everything, I mean everything, between two
characters that the users gets prompted for when launching the macro.

Sounds simple but I could not found anywhere an extensive description of
the syntax to use for search and replace.

Can a good soul show me the light?

Thanks
 
D

Doug Robbins - Word MVP

The following code should do what you want:

Dim delrng As Range
Dim char1 As String
Dim char2 As String
char1 = InputBox("Enter the first character of the text that you want to
delete", "Deleter")
char2 = InputBox("Enter the last character of the text that you want to
delete", "Deleter")
Set delrng = ActiveDocument.Range
Do While InStr(delrng, char1) > 0
delrng.start = delrng.start + InStr(delrng, char1) - 1
If InStr(delrng, char2) > 0 Then
delrng.End = delrng.start + InStr(delrng, char2)
delrng.Delete
Set delrng = ActiveDocument.Range
End If
Loop


--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 
J

John Doue

Doug said:
The following code should do what you want:

Dim delrng As Range
Dim char1 As String
Dim char2 As String
char1 = InputBox("Enter the first character of the text that you want to
delete", "Deleter")
char2 = InputBox("Enter the last character of the text that you want to
delete", "Deleter")
Set delrng = ActiveDocument.Range
Do While InStr(delrng, char1) > 0
delrng.start = delrng.start + InStr(delrng, char1) - 1
If InStr(delrng, char2) > 0 Then
delrng.End = delrng.start + InStr(delrng, char2)
delrng.Delete
Set delrng = ActiveDocument.Range
End If
Loop
Thanks Doug, it is exactly what I was looking for. I just added

If char1 = char2 Then
char2 = InputBox("Error. Reenter the last character of the text that you
want to delete", "Deleter")
End If

after the second input box in case the user uses twice the same character.

Thanks a lot.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top