AmongTheShadows
AmongTheShadows

Reputation: 29

Replacing text in Text Files

I created a text file that contains different sections. I need to pull the information at a later time.

I split each line of the txt file to have each variable.

Example:

[Title]The Maps[TitleEnd]  
[Name]Smith,John[NameEnd]  
[Subject]Mythical Creatures[SubjectEnd]  
[Text]Today i learned about this information and blah blah blah[TextEnd]  
etc.

I need to open the txt file, find the correct brackets i.e. [Text] to [TextEnd] then replace it.

Example:

[Text]Today i learned about this information and blah blah blah[TextEnd]

to

[Text]Today i learned about this information and  i learned more things and blah blah blah[TextEnd]

I looked at a couple of examples. One has gotten me close but instead of replacing 1 line, it puts everything on 1 line.

Private Sub SavePro_Click()

    IRBNum = ThisDocument.IRBNetID
    FilePath = "Abstract.txt"
    TextFile = FreeFile
    Open FilePath For Input As #1
    StrFinal = "[Text]*"
    While EOF(1) = False
        Line Input #1, strline
        StrFinal = StrFinal + ModifyText(strline)
    Wend
    StrFinal = Left(StrFinal, Len(StrFinal) - 2)
    Close 1
    Open FilePath For Output As #1
    Print #1, StrFinal
    Close #1

End Sub

Function ModifyText(ByVal strInput As String) As String
    Dim arrString() As String
    Dim strOutput As String

    arrString = Split(strInput, " ")
    strOutput = arrString(0) + " " + SubText.Text
    ModifyText = strOutput
    
End Function

Upvotes: 2

Views: 93

Answers (1)

CDP1802
CDP1802

Reputation: 16224

If you use an XML format

<xml>
 <Title>The Maps</Title>
 <Name>Smith,John</Name>
 <Subject>Mythical Creatures</Subject>
 <Text>Today i learned about this information and blah blah blah</Text>
</xml>

most of the code has been written for you.

Option Explicit

Sub update()

    Dim xDoc, oNode
    Set xDoc = CreateObject("MSXML2.DOMDocument.6.0")
    xDoc.Load Path & "\Abstract.xml"
    
    Set oNode = xDoc.SelectSingleNode("xml/Text")
    MsgBox "Text: " & oNode.nodeTypedValue
    oNode.nodeTypedValue = "Today i learned about this information " & vbCrLf & _
           "and  i learned more things and blah blah blah"
       
    xDoc.Save Path & "\Abstract.xml"
    
End Sub

Upvotes: 1

Related Questions