Replacing text in Text Files - excel

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

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

Related

VBA Excel Macro error: 1004 unable to get the substitute property of the WorkbooFunction class

I am using a vba macro to find a big string in a text file.
For that I read the text file , read the text to compare (which is saved in one of the cell). After that i would replace CRLF with CR (since the saved text does not contain CRLF). Then compare. Its working fine if the file size is less. But throwing the error when the file size is high (Around 50 KB is fine).
Any guess about the maximum size of the file?
The below part of the code is throwing error
Open LogFilePath For Input As #iFile
strFileContent = Input(LOF(iFile), iFile)
Close #iFile
strFileContent = Application.WorksheetFunction.Substitute(strFileContent, vbCrLf, "")
strSearch = Application.WorksheetFunction.Substitute(strSearch, vbLf, "")
strFileContent = Application.WorksheetFunction.Substitute(strFileContent, vbTab, " ")
If InStr(1, strFileContent, strSearch, vbBinaryCompare) > 0 Then
SearchTextFile = "success"
Else
SearchTextFile = "failed"
End If
Any guess or suggestion please.
I note the error refers to the Substitute property and that you are using Application.WorksheetFunction.Substitute.
Personally, in VBA I always tend to use the REPLACE function which works in the same way.
I also use this when processing some large .txt files (20,000 rows/30MB) and don't encounter problems with it.
The Substitute is more for use e.g. with a cell formula. You should try following code snippet using Replace for your needs.
Private Sub CommandButton1_Click()
Dim LogFilePath As String
Dim ifile As Integer
ifile = 1
LogFilePath = "D:/_working/application-log-file-small.txt"
strSearch = "Temp Path :"
Open LogFilePath For Input As #ifile
strFileContent = Input(LOF(ifile), ifile)
Close #ifile
'--- Show len of file content string -----
MsgBox (Len(strFileContent))
strFileContent = Replace(strFileContent, vbCrLf, "")
strSearch = Replace(strSearch, vbLf, "")
strFileContent = Replace(strFileContent, vbTab, " ")
If InStr(1, strFileContent, strSearch, vbBinaryCompare) > 0 Then
SearchTextFile = "success"
MsgBox ("success")
Else
SearchTextFile = "failed"
MsgBox ("failed")
End If
End Sub

Ignoring blank lines and spaces in text files when reading

I have a text file with file addresses listed line by line.
Sometimes, however, the users go in there and accidentally add a space or a blank line between the addresses and that crashes the entire code.
How could I avoid this when reading the file using VBA?
This is the current block used to open the text file and read addresses line by line:
Set ActiveBook = Application.ActiveWorkbook
PathFile = ActiveWorkbook.Path & "\FilePaths.txt"
Open PathFile For Input As #1
Do Until EOF(1)
Line Input #1, SourceFile
Set Source = Workbooks.Open(SourceFile)
You will add two lines which will ignore blank lines and spaces like this:
Line Input #1, SourceFile
SourceFile = Trim(SourceFile) '~~> This will trim all the spaces
If Not SourceFile = "" Then '~~> This will check if lines is empty
Set Source = Workbooks.Open(SourceFile)
Suggest you add further code to
test if the file actually exists
test if the file is of a valid type for excel to open
code
Dim SourceFile As String
Dim PathFile As String
Set ActiveBook = Application.ActiveWorkbook
PathFile = ActiveWorkbook.Path & "\FilePaths.txt"
Open PathFile For Input As #1
Do Until EOF(1)
Line Input #1, SourceFile
SourceFile = Trim$(SourceFile)
If Len(Dir(ActiveWorkbook.Path & "\" & SourceFile)) > 0 Then
Select Case Right$(SourceFile, Len(SourceFile) - InStrRev(SourceFile, "."))
Case "xls", "xls*"
Set Source = Workbooks.Open(ActiveWorkbook.Path & "\" & SourceFile)
Case Else
Debug.Print "source not valid"
End Select
End If
Loop
Thanks for the code.
I did some small changes so I can reuse it in many different cases and call at any point of the code, using up to 3 different args (you may increase if you wish). like this below example.
note: you may change "totalBananas,EN2003" to anything you find impossible to exist in your files... I used it this way because I am not sure how to declare the args as optional :-p I don't think they are really possible to be optional anyway.
...
Call FixTextFile(file_name, "blabla", "0000", "")
...
Sub FixTextFile(inFile As Variant, fixArg1 As String, fixArg2 As String, fixArg3 As String)
Dim resArg1, resArg2, resArg3 As Long
Dim outFile As String
Dim data As String
If fixArg1 = "" Then fixArg1 = "totalBananas,EN2003"
If fixArg2 = "" Then fixArg2 = "totalBananas,EN2003"
If fixArg3 = "" Then fixArg3 = "totalBananas,EN2003"
Open inFile For Input As #1
outFile = inFile & ".alt"
Open outFile For Output As #2
Do Until EOF(1)
Line Input #1, data
resArg1 = InStr(1, data, fixArg1)
resArg2 = InStr(1, data, fixArg2)
resArg3 = InStr(1, data, fixArg3)
If Trim(data) <> "" And resArg1 < 1 And resArg2 < 1 And resArg3 < 1 Then
Print #2, data
End If
Loop
Close #1
Close #2
Kill inFile
Name outFile As inFile
MsgBox "File alteration completed!"
End Sub

vba read all text in a text file?

I am trying to use vba to read all text in a text file and display it in an excel message box. the problem I have is whilst this is in effect working, it displays each line of text in a separate message box when instead I want it all in one?
can someone please show me where I am going wrong. thanks
If Range("L" & ActiveCell.Row).Value = "Performance" Then
Dim FilePath As String
Dim strLine As String
FilePath = "\\UKSH000-FILE06\Purchasing\New_Supplier_Set_Ups_&_Audits\ATTACHMENTS\" & Range("C" & ActiveCell.Row).Value & "\performance.txt"
Open FilePath For Input As #1
While EOF(1) = False
'read the next line of data in the text file
Line Input #1, strLine
'print the data in the current row
MsgBox strLine
'increment the row counter
i = i + 1
Wend
Close #1
End If
Within your loop you have to concatenate all the lines a string variable and output the result at the end. It's basically like this:
Dim Total As String
' ...
While EOF(1) = False
'read the next line of data in the text file
Line Input #1, strLine
Total = Total & vbNewLine & strLine
'increment the row counter
i = i + 1
Wend
MsgBox Total
Note: While this solution is working, for large files it may not be very efficient due to the fact that what looks like a concatenation in code, in fact means copying the existing content to a new memory location, and then inserting the new line's string. That is done for every line. So for 1000 lines, the incresingly large total string is copied around 999 times.
You need to accumulate the text in a separate string:
Write Dim strAll As String before the loop.
Replace the MsgBox in the loop with strAll = strAll & strLine.
After the loop, use MsgBox strAll
& is used to join strings in VBA. You could separate the individual lines with a space:
strAll = strAll & " " & strLine.
Or even multi-line
strAll = strAll & vbCrLf & strLine.
where vbCrLf is a VBA constant which means "carriage return followed by line feed". You'll introduce an extra space / line feed at the start of the string but I'll leave that for you to fix!

EXCEL VBA Write - Read File - BUG?

I've been wracking my brains with a file input problem, I've finally got it down to two problems, I can get past the error 62, "Read past End of file", but this one I can't get past.
Can someone tell me if I'm doing anything wrong / verify?
Basically the (this) code writes two lines#
?xml version="1.0"?
A Second Line
the debug statement in Part 1 (write file) prints the text as
?xml version="1.0"?
A Second Line
the debug statement in Part 2 (read file) prints the text as
ÿþ?xml version="1.0"?
A Second Line
As you can see, there are two extra characters being added to the either the input or
the output stream at the beginning of the file.
A second line has been added for completeness to show in more detail that it is only the first line that is being screwed.
When I look through Notepad there is nothing extra, what/where are these extras coming from?
Any thoughts, thanks in advance,
regards
Seán
Sub writeXMLTest()
'Part 1 - Write the file
Dim FSO As Object
Dim NewFile As Object
Dim FullPath As String
Dim XMLFileText As String
FullPath = "E:\TESTFILE.xml"
'On Error GoTo Err:
Set FSO = CreateObject("Scripting.FileSystemObject")
Set NewFile = FSO.CreateTextFile(FullPath, 1, 1)
XMLFileText = ""
XMLFileText = XMLFileText & "?xml version=" & Chr(34) & "1.0" & Chr(34) & "?" & vbNewLine
NewFile.Write (XMLFileText)
Debug.Print XMLFileText
XMLFileText = XMLFileText & "A Second Line" & vbNewLine
NewFile.Write (XMLFileText)
Debug.Print XMLFileText
NewFile.Close
'Part 1 - Complete
'Part 2 - Now to read the file
Dim FileNum As Integer, i As Integer
Dim s As String
' fpath = Application.GetOpenFilename
FileNum = FreeFile()
Open FullPath For Input As #FileNum
i = 1
While Not EOF(FileNum)
Line Input #FileNum, s ' read in data 1 line at a time
Debug.Print s
Wend
End Sub
Just a quick shot: Generally, xml-files use UTF8 encoding. But the FileSystemObject cannot handle UTF8. You can do this (read and write UTF8-Files in VBA) with an ADODB.Stream object - you'll find examples across the web.

Refer to line below search text in text file

I have data such as the following in a text file:
Member A
Diameter 60 in
Thickness 1 in
Yield Stress 50 ksi
Brace B
Diameter 54 in
Thickness 1 in
Yield Stress 50 ksi
I need to extract numerical diameter (or thickness, or yield stress) when a string of text "Member A" is found within a long text file. Data is always in same order.
I can extract data that is on the same line as the text I'm searching for using "Trim" / "Mid". I do not know how to refer to "the line below" the text I'm searching for.
My code:
Sub jtdtlextract()
Dim str, str1, strOutPut, strBrcAngle, strComnJt, strChrdDia As String
Dim FileToOpen, FileConverted, strRun, lngReturn, fs, f, s, ff
FileToOpen = Application.GetOpenFilename("All Files (*.*), *.*")
If FileToOpen <> False Then
MsgBox FileToOpen, 0, "Open File"
End If
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(FileToOpen)
FileConverted = UCase(f.ParentFolder.Path) & "\jt_dtls_extracted.txt"
Open FileToOpen For Input Access Read Shared As #1
Open FileConverted For Output Access Write Shared As #2
Do Until EOF(1)
Line Input #1, str
str1 = LTrim(str)
If Left(str1, 31) = "Detailed Review Report of Joint" Then
strComnJt = Trim(Mid(str1, 35, 4))
strOutPut = "Common_Jt" & Space(1) & strComnJt
Print #2, strOutPut
End If
'I have a lot more information to extract from the text file
'I was hoping to use a method similar to above since it's
'fairly simple and I have no coding experience, the code
'above only works when the information needed is on the
'same line as the information searched for. Was written
'by someone else.
Loop
Close #1
Close #2
strRun = "Notepad.exe " & FileConverted
lngReturn = Shell(strRun)
End Sub
You'll need some state-management code to keep track of where you are in the file.
If the file is not too big you don't need full-streaming and can use full-buffering in an array.
Then you can naturally scan this array using simple indexing :
name = lines(i)
diameter = parseDiameter(lines(i+1))
thickness = parseThickness(lines(i+2))
yieldStress = parseYieldStress(lines(i+3))
i = i + 5
Do Until EOF(1)
Line Input #1, str
str1 = LTrim(str)
If Left(str1, 31) = "Detailed Review Report of Joint" Then
strComnJt = Trim(Mid(str1, 35, 4))
strOutPut = "Common_Jt" & Space(1) & strComnJt
Print #2, strOutPut
Line Input #1, strDiscardThisLine
Line Input #1, str3rdLine
strOutPut = Trim(Mid(str3rdLine,35,4))
Print #2, strOutPut
End If

Resources