Link to home
Start Free TrialLog in
Avatar of waltforbes
waltforbesFlag for Bahamas

asked on

How to replace text in a text file with text from another file?

Points of My Scenario:

1. I have an Excel with two columns: column A lists obsolete group names, and column B lists the replacement group names (see Excel file illustration below).

User generated image


2. I have a text file containing all the obsolete group names along with the members of each group immediately beneath the group's name (see text file illustration below).

User generated image



3. I need the obsolete group names in the text file to be replaced with the corresponding replacement group names provided in the Excel file's column B.


QUESTION: What can I do to replace the obsolete group names in the text file with replacement group names from the Excel file's column B?

Avatar of Subodh Tiwari (Neeraj)
Subodh Tiwari (Neeraj)
Flag of India image

Assuming both the Excel Macro-Enabled File and the Text File are placed in the same folder, you may try something like this...

Sub ReplaceGroupsInTextFile()
Dim strFile As String
Dim strFilePath As String
Dim strFileName As String
Dim strData As String
Dim ws As Worksheet
Dim lr As Long
Dim Rng As Range
Dim Cel As Range
Dim i As Long

strFilePath = ThisWorkbook.Path & "\"
strFileName = "TEXTFILE.txt"
strFile = strFilePath & strFileName

Set ws = ThisWorkbook.Worksheets("Sheet1")
lr = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set Rng = ws.Range("A2:A" & lr)

i = FreeFile
strData = Space(FileLen(strFile))

Open strFile For Binary Access Read Write As #i
Get #i, , strData
Close #i

With CreateObject("VBScript.RegExp")
    .Global = False
    For Each Cel In Rng
        .Pattern = Cel.Value
        If .Test(strData) Then
            strData = .Replace(strData, Cel.Offset(0, 1).Value)
        End If
    Next Cel
End With

Open strFile For Output As #i
Write #i, strData
Close #i

End Sub

Open in new window

Replace Group in Text File.xlsm
The code is placed on Module1 in the attached Excel file.
Avatar of waltforbes

ASKER

1. I Googled and learned I must use Alt+F11 to access the VBscript code.

2. Should I make the following changes in the code?
  (a) ThisWorkbook.Path to the actual name of the Excel file (all files in same folder, so will I need to specify full path?)
  (b) TEXTFILE.txt to the actual name of the text file
  (c) ThisWorkbook.Worksheets("Sheet1") to the ExcelFile'sName("tab-name")

3. Is there anything else I will have to change in the code?


1. I Googled and learned I must use Alt+F11 to access the VBscript code. 
Yes, this is the way to access the Macro, the other thing you may try is, insert either a Form Control Button or a Shape on the Sheet and assign the Macro to it and then you may run the Macro by pressing the button or shape.

2. Should I make the following changes in the code?
  (a) ThisWorkbook.Path to the actual name of the Excel file (all files in same folder, so will I need to specify full path?) YES
  (b) TEXTFILE.txt to the actual name of the text file YES
  (c) ThisWorkbook.Worksheets("Sheet1") to the ExcelFile'sName("tab-name") YES

3. Is there anything else I will have to change in the code? 

You correctly figure it out that what to change in the code.
I am consistently getting an error at line 12:
User generated image
Also, here is what happens when I press the Play button:
User generated image
Once I click OK button on the pop up error, the following highlights occur:
User generated image
I did the following troubleshooting steps:
1. I put the actual data into your XLSM file (previously, I had placed the actual data in a separate XLSX file - which I referenced in the macro code).

2. I updated line 12 of the code by (a) placing quotes around the path, and (b) correcting the filename to ThisWorkbook.xlsm, which now contains the actual data and the macro.

3. I also updated line 16 to specify this macro-enabled Excel file containing the actual data.

4. The previous errors disappeared, and the following new error appeared:
User generated image
The correct line is as below to set the worksheet...
Set ws = ThisWorkbook.Worksheets("Sheet1")

If the name of your file is ThisWorkbook.xlsm, the ThisWorkbook in the above line will refer to your workbook.
Also, strFilePath should be equal to the full path of your Text File in double-quotes.
So e.g. if the text file is saved in a folder called Test at my Desktop, the strFilePath should be equal to "C:\Users\sktneer\Desktop\Test\TEXTFILE.txt"

i.e.
strFilePath = "C:\Users\sktneer\Desktop\Test\TEXTFILE.txt"
I have made the corrections; we are getting closer (I believe). Here's the new error:
User generated image
I also noticed that when I clicked on "Debug", the following highlight appears:
User generated image
Remove the & "\" from the variable strFilePath, it should be like below...

strFilePath = "C:\temp\TEXTFILE.txt"

Why you have saved your file in the temp folder? Is it a manually created folder in C drive?

I saved to the temp directory because I feared that the macro was having an issue with the folder-depth of the original path.
I will now make the correction you mentioned above and update you.
Currently, I get "Run-time error 53: File not found". Below shows error + existence of the files:
User generated image
Also, when I press the Debug button this time, I get the following highlight again:
User generated image
Place the text file in a normal folder and then test it again.
I got the following result (notice the path change):
User generated image
ASKER CERTIFIED SOLUTION
Avatar of Subodh Tiwari (Neeraj)
Subodh Tiwari (Neeraj)
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oh wow, Neeraj! It worked like a charm!

After a new hours of sleep, I see clearly the beauty & simplicity of the code (declaring strFilePath and strFileName variables, etc).

Although I don't know about VBscripting you are right: I should have been able to look at your code and at least understand how to use the path and file variables. Shame on me.

Maybe the sleep was what I needed...Lol!

A great many thanks for your genius and patience. You've enabled me to stay on project schedule!
You're welcome! Glad it worked for you as desired in the end.
Thanks for the feedback and testimonial, appreciate it.

Have a great time ahead!