Robert English
Robert English

Reputation: 223

Insert spaces in particular places on particular lines in .txt file

I've been trying to write a program that opens a text file and inserts spaces after the 5th, 6th and 7th word for every line beginning with C_PIN.

I feel that I have it almost complete but I've benn getting run-time errors 5 and 438.

Example text being read:


COMP C48 66250110810 cap sc_cap.0603_H9 43.3959 74.3331 1 0
C_PROP (PB_FREE,"Y") (VALUE,"10nF") (TOLER,"10%") (PART_NAME,"06035C103K4T2A")
C_PIN C48-1 43.3959 75.0951 1 1 0 sp.0603_H9.1 /N$1567
C_PIN C48-2 43.3959 73.5711 1 1 0 sp.0603_H9.2 GN


An extra space is required after the 1 1 0

Here's where I think the problem in my code lies:

x = " "
Do While Not EOF(infilenum%)
 Line Input #infilenum%, a$
  If Left$(a$, 5) = "C_PIN" Then
   For Each x In InStr
   'If InStr(strText, " ") Then
     w = w + 1
    'w = strText.Split
     For w = 5 To w = 7
      My.Computer.FileSystem.WriteAllText (infilename$)
      strText = My.Computer.FileSystem.ReadAllText(infilename$).Replace(w, x + w)
      vb.newline

Any help is much appreciated!

Upvotes: 1

Views: 1281

Answers (2)

brettdj
brettdj

Reputation: 55692

I played with an alternative version that uses a to make a single shot replacement

While it looks a little complicated, the plus - other than a single shot replacement - is that it only will alter lines that

  • start with C_PIN
  • have (at least) a further 6 words

This sample take your initial file, and saves a second version with the padded spacing.

Upated for additional requirement, using two separate regexp replacements

Sub ReDo()
Dim objFso As Object
Dim objFil As Object
Dim objFil2 As Object
Dim objRegex As Object
Dim strFile As String
Dim strAll As String

strFil = "c:\temp\REnglish.txt"
strFil2 = "c:\temp\REnglish2.txt"

Set objFso = CreateObject("Scripting.FileSystemObject")
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "(\nC_PIN\s)((\b[^\s]+\b\s){3})(\b[^\s]+\b\s)(\b[^\s]+\b\s)(\b\d\b\s)"
.Global = True
Set objFil = objFso.OpenTextFile(strFil)
strAll = objFil.ReadAll
Set objFil2 = objFso.createtextfile(strFil2)
strAll = .Replace(strAll, "$1$2$3$4 $5 $6 ")
.Pattern = "(\nC_PIN\s)((\b[^\s]+\b\s){3})(\b[^\s]+\b\s)(\b[^\s]+\b\s)(\b\d{2,}\b\s)"
objFil2.write .Replace(strAll, "$1$2$3$4 $5 $6")
End With
objFil.Close
objFil2.Close
End Sub

Upvotes: 1

LS_ᴅᴇᴠ
LS_ᴅᴇᴠ

Reputation: 11181

For Each x In InStr

isn't valid in any way!!!

You can use Split and Join:

If Left(a, 5) = "C_PIN" Then
    va = Split(a, " ")
    va(4) = va(4) & " " 'Add extra space
    va(5) = va(4) & " "
    va(6) = va(4) & " "
    a =  Join(va, " ") 'Join with extra spaces added
End If

Now you can write the string.

Upvotes: 3

Related Questions