PDA

View Full Version : How to: If First 12 Characters in line = "/", Delete character



l0aded
07-30-2014, 12:13 PM
As title says, I am trying to scan just the first 12 characters in each line and if it contains a "/" delete that character. So for example:

KB4024/AB
AC3402/AB

would become

KB4024AB
AC3402AB

I am fairly new to vba but I'd imagine it would need to use arrays? Another way that seems lengthy is to use
ActiveDocument.Paragraphs(n). _
Range.Characters(m) and just keep looping around till m reaches 12. Would this method work?

Thanks!

macropod
07-30-2014, 02:40 PM
You could use a wildcard Find/Replace, without the need for VBA...
Find = ([^13^l][!^13^l/]{1,12})/
Replace = \1

l0aded
07-30-2014, 03:06 PM
Didn't know about wildcards =X. Simple solutions to simple problems I suppose haha. Thanks

Geoff
08-18-2014, 01:30 PM
Dim TargetString as String. ' the string to be searched
Dim Location as Integer
Dim ResultString as String. ' the string without the /

Location = Instr(TargetString, "/")

If Location = 0 Or Location >12 Then
ResultString = TargetString
' Because the / wasn't found (0) or
' wasn't in the first 12 characters (>12)
Else
ResultString = Left(TargetString, Location-1) & Right(TargetString, Len(TargetString) - Location)
End If


Geoff

macropod
08-18-2014, 03:33 PM
Geoff: A straightforward Find/Replace would be far faster. The longer the document, the faster it would be by comparison.

gmayor
08-18-2014, 10:02 PM
If you want Paul's replace function in a macro then

Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
Do While .Execute(FindText:="([^13^l][!^13^l/]{1,12})/", _
ReplaceWith:="\1", _
MatchWildcards:=True)
oRng.Collapse wdCollapseEnd
Loop
End With

should do the job.

macropod
08-18-2014, 10:42 PM
Graham,

There's no need for the loop:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([^13^l][!^13^l/]{1,12})/"
.Replacement.Text = "\1"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
Application.ScreenUpdating = True
End Sub

gmayor
08-18-2014, 11:10 PM
Indeed - more than one way to skin a cat :)

Geoff
08-19-2014, 12:38 AM
Maybe I took the question too literally. I thought he only wanted to replace the / if it occurred in the first twelve characters and not if it was present further into the string.

Geoff

macropod
08-19-2014, 01:04 AM
The F/R expression and code I've posted does only replace the / if it occurs in the first twelve characters. It ignores whatever may be further along.