BiblioPhillip
BiblioPhillip

Reputation: 21

VBA - in Word, check if selection contains specified character string

I have a word document with multiple lines of text. I want to determine which of those lines (or paragraphs if longer than a line) contains the string " / " and delete those lines that don't have one.

This is an example of what i've been trying to achieve. The If statement obviously is the part that doesn't work at present but i've been having trouble working out a solution.

Selection.WholeStory
nLines = Selection.Range.ComputeStatistics(Statistic:=wdStatisticParagraphs)
Selection.HomeKey Unit:=wdStory
Do While StartNumber2 < nLines
StartNumber2 = StartNumber2 + 1
Selection.HomeKey Unit:=wdLine
Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
If Selection.Text = " / " Then
Selection.MoveDown Unit:=wdLine, Count:=1
Else: Selection.Delete Unit:=wdCharacter, Count:=1
End If
Loop

This is an example of text it'll be checking. I need it to delete 2 & 4 and leave 1 & 3:

  1. Back In Black / ACDC (3:54) --
  2. Tonight (2:44) --
  3. Lucy in the Sky with Diamonds / The Beatles (4:22) --
  4. Random Song Name (3:33) --

Any help would be appreciated.

Upvotes: 0

Views: 4843

Answers (1)

BiblioPhillip
BiblioPhillip

Reputation: 21

Thanks Comintern. I thought there would be a simple way and InStr did the job.

Selection.WholeStory
nLines = Selection.Range.ComputeStatistics(Statistic:=wdStatisticParagraphs)

Selection.HomeKey Unit:=wdStory
Do While StartNumber2 < nLines
StartNumber2 = StartNumber2 + 1
Selection.HomeKey Unit:=wdLine
Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
If InStr(Selection, " / ") > 0 Then
Selection.MoveDown Unit:=wdLine, Count:=1
Else: Selection.Delete Unit:=wdCharacter, Count:=1
End If
Loop

Upvotes: 1

Related Questions