View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Bernie Deitrick Bernie Deitrick is offline
external usenet poster
 
Posts: 5,441
Default Modifying text files with VBA?

Dave,

Try the macro below, which assumes that the files have a TXT extension. You
will be asked to choose the files.

HTH,
Bernie
MS Excel MVP

Option Explicit
Sub ReplaceSpecificLines()
Dim ReadStr As String
Dim FileName1 As String
Dim FileName2 As String
Dim OrigFNum As Integer
Dim RepFNum As Integer
Dim FileNumOut As Integer
Dim Counter As Double

Counter = 1

FileName1 = Application.GetOpenFilename( _
"Text Files (*.txt),*.txt", _
, "Pick the Original File")
If FileName1 = "" Then End

FileName2 = Application.GetOpenFilename( _
"Text Files (*.txt),*.txt", _
, "Pick the Replacement File")
If FileName2 = "" Then End

OrigFNum = FreeFile()
Open FileName1 For Input As #OrigFNum
RepFNum = FreeFile()
Open FileName2 For Input As #RepFNum
FileNumOut = FreeFile()
Open "Merged File.txt" For Output Access Write As #FileNumOut


Do While Seek(OrigFNum) <= LOF(OrigFNum) And Counter < 274
Application.StatusBar = "Processing line " & Counter
Line Input #OrigFNum, ReadStr
Print #FileNumOut, ReadStr
Counter = Counter + 1
Loop
Do While Seek(RepFNum) <= LOF(RepFNum) And Counter < 327
Application.StatusBar = "Processing line " & Counter
Line Input #RepFNum, ReadStr
Print #FileNumOut, ReadStr
Line Input #OrigFNum, ReadStr
Counter = Counter + 1
Loop
Do While Seek(OrigFNum) <= LOF(OrigFNum)
Counter = Counter + 1
Application.StatusBar = "Processing line " & Counter
Line Input #OrigFNum, ReadStr
Print #FileNumOut, ReadStr
Loop

Close #OrigFNum
Close #RepFNum
Close #FileNumOut

Application.StatusBar = False

End Sub

"Dave Parker" wrote in message
om...
I have two (ASCII) text files (FileA and FileB), and I need to replace
a portion of FileA with the contents of FileB. The position of the
text in the files is fixed - I just need to replace lines 274-326 in
FileA with lines 1-53 of FileB.

I've tried a subroutine that reads both files to a workbook, merges
the required portion, then saves a text formatted file. However,
portions of the files are space delimited and others are comma
delimited so this method doesn't work properly. I think I need to
directly access and modify the files from VBA (of course, I'm open to
other suggestions).

Thank you for any help you can provide.
Dave