Solved

VB file search and Replace

Posted on 1998-09-09
11
347 Views
Last Modified: 2012-05-04
I want a procedure that will search and replace strings in a text file.

I want this to happen using VB
Is there a dll or activeX dll that allready does this?

eg.
Public Sub SearchAndReplace(pstrFindThis as string, pstrReplaceWithThis as string, pstrFilename as string)

any help appreciated
0
Comment
Question by:pcrimm
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
11 Comments
 
LVL 4

Expert Comment

by:mcix
ID: 1433819
I have a function that does that...

If you want it, I will e-mail you the source.
0
 

Author Comment

by:pcrimm
ID: 1433820
I would greatly appreciate that.
pcrimm@optum.com
0
 
LVL 14

Accepted Solution

by:
waty earned 180 total points
ID: 1433821
HEre is code. If you want, I can create the full function :

You could use the following code :

dim sTmp     as string
dim sSgmlIn  as string

' *** Open the file to read all the text file
nSgmlIn = FreeFile
Open sSgmlCurrent For Input Access Read As #nSgmlIn
sSgmlIn = ""
Do While EOF(nSgmlIn) = False
   Line Input #nSgmlIn, sTmp
   sSgmlIn = sSgmlIn & sTmp
Loop
Close #nSgmlIn

sTmp = ReplaceString(sSgmlIn, pstrFindThis, pstrReplaceWithThis)

nPrintOut = FreeFile
Open sPSOut For Binary Access Write As #nPrintOut
Write #nPrintOut, , sTmp
close #nPrintOut


Function ReplaceString(sSearch As String, sSearchFor As String, sReplaceWith As String) As String
   ' *** Searches the sSearch variable for sSearchFor
   ' *** and replaces it with sReplaceWith.

   On Error GoTo ERROR__ReplaceString

   Dim lFoundLoc        As Long   ' Location of match.
   Dim lLenRemove       As Long   ' Length of string being replaced.
   
   ' *** Set length of original text to skip.
   lLenRemove = Len(sSearchFor)    ' Set location of match.
   
   lFoundLoc = InStr(1, sSearch, sSearchFor)
   
   ' If sSearchFor isn't found in sSearch
   ' just return the original string.
   If lFoundLoc = 0 Then
      ReplaceString = sSearch
      ' If match is found, return original string up to match
      ' location, concatenate new text, and search the rest of
      ' the string recursively for additional matches.
   Else
      ReplaceString = left(sSearch, lFoundLoc - 1) & sReplaceWith & ReplaceString(Mid(sSearch, lFoundLoc + lLenRemove), sSearchFor, sReplaceWith)
   End If

EXIT_ReplaceString:
   Exit Function

ERROR__ReplaceString:
   ' Print error to Debug window and don't interrupt query.
   Debug.Print "Error Replacing String """ & sSearchFor & """ with """ & sReplaceWith & """ in text """ & sSearch & """"
   ' If there is an error, return original string
   ' and exit the function.        ReplaceString = sSearch
   Resume EXIT_ReplaceString

End Function

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 14

Expert Comment

by:waty
ID: 1433822
Here is the complete function
Function FileReplaceString(sFile As String, sSearchFor As String, sReplaceWith As String) As Boolean
   ' *** Searches in sFile file for sSearchFor
   ' *** and replaces it with sReplaceWith.

   Dim nFile      As Integer
   
   Dim sTmp       As String
   Dim sText      As String
   
   On Error GoTo ERROR_FileReplaceString
   
   ' *** Open the file to read all the text file
   nFile = FreeFile
   Open sFile For Input Access Read As #nFile
   sText = ""
   Do While EOF(nFile) = False
      Line Input #nFile, sTmp
      sText = sText & sTmp
   Loop
   Close #nFile
   
   ' *** Replace the text
   sTmp = ReplaceString(sText, sSearchFor, sReplaceWith)
   
   ' *** Delete the previous file
   Kill sFile
   
   ' *** Save as temporary
   nFile = FreeFile
   Open sFile For Binary Access Write As #nFile
   Write #nFile, , sTmp
   Close #nFile

   FileReplaceString = True
   Exit Function

ERROR_FileReplaceString:
   FileReplaceString = False
   
   Exit Function

End Function


Function ReplaceString(sSearch As String, sSearchFor As String, sReplaceWith As String) As String
   ' *** Searches the sSearch variable for sSearchFor
   ' *** and replaces it with sReplaceWith.

   On Error GoTo ERROR__ReplaceString

   Dim lFoundLoc        As Long   ' Location of match.
   Dim lLenRemove       As Long   ' Length of string being replaced.
   
   ' *** Set length of original text to skip.
   lLenRemove = Len(sSearchFor)    ' Set location of match.
   
   lFoundLoc = InStr(1, sSearch, sSearchFor)
   
   ' If sSearchFor isn't found in sSearch
   ' just return the original string.
   If lFoundLoc = 0 Then
      ReplaceString = sSearch
      ' If match is found, return original string up to match
      ' location, concatenate new text, and search the rest of
      ' the string recursively for additional matches.
   Else
      ReplaceString = left(sSearch, lFoundLoc - 1) & sReplaceWith & ReplaceString(Mid(sSearch, lFoundLoc + lLenRemove), sSearchFor, sReplaceWith)
   End If

EXIT_ReplaceString:
   Exit Function

ERROR__ReplaceString:
   ' Print error to Debug window and don't interrupt query.
   Debug.Print "Error Replacing String """ & sSearchFor & """ with """ & sReplaceWith & """ in text """ & sSearch & """"
   ' If there is an error, return original string
   ' and exit the function.        ReplaceString = sSearch
   Resume EXIT_ReplaceString

End Function
0
 

Author Comment

by:pcrimm
ID: 1433823
Here is my curriosity.
I am not interested in the logistics of searching and replacing.(I am cool with that)
I AM troubled by the fact you can not open a file, muck with it(ie search, replace, go back to the top, navigate, write a few lines here, a few characters there), and then close it.
What is this open, read, kill, recreate? (not you Wady, VB)
SPEED is necessary
many files, many large files,
which brings a problem to Wady's proposal (cant do the loop with large files)

I want to open a file, find the search, change it, then close it

I understand you could input line by line, while searching each line and then add the new line to a temp file, but why cant you go back and delete a line you found in the open file that had the search string in it?

Otherwise I am reluctantly willing to create a component in C++ that will do the job and use that in vb. (but has that allready been done?)

I need a therapist, anyone?????
0
 
LVL 14

Expert Comment

by:waty
ID: 1433824
You could read the file at one time

' *** Open the file to read all the text file
nFile = FreeFile
Open sFile For Input As #nFile
sText = InputB(FileLen(sFile), nFile)
Close #nFile

0
 

Author Comment

by:pcrimm
ID: 1433825
Waty, the problem is, a text file the size of 2 megs will die if you try to load it into a vb string.
Performance on the machine will suffer.
And I would still have to write the entire changed string to another file.(Because the end result is to change the contents of the file.)
0
 
LVL 14

Expert Comment

by:waty
ID: 1433826
Ok.
You could not change the same file when you are reading it.

The solution is that you open the input file, open an output file using a temporary name, read by 32k, replace string in all those 32k, write this in the output file. When all the input file is done, copy the temporary over the input file.


0
 
LVL 14

Expert Comment

by:waty
ID: 1433827
Ok.
You could not change the same file when you are reading it.

The solution is that you open the input file, open an output file using a temporary name, read by 32k, replace string in all those 32k, write this in the output file. When all the input file is done, copy the temporary over the input file.

If you want, I can write this for you.

0
 

Author Comment

by:pcrimm
ID: 1433828
Waty, Post the code and the spoils are yours.
I truely appreciate your help

Yours,
Paul
0
 
LVL 14

Expert Comment

by:waty
ID: 1433829
Here is the code

Use the function defines in previous comments, and add those two funtions :

Private Declare Function GetTempPathA Lib "kernel32" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Declare Function GetTempFileNameA Lib "kernel32" (ByVal lpszPath As String, ByVal lpPrefixString As String, ByVal wUnique As Long, ByVal lpTempFileName As String) As Long
Private Const UNIQUE_NAME = &H0

Public Function GetTempFileName() As String
   ' *** Returns a unique tempfile name.
   
   Dim sTmp    As String
   Dim sTmp2   As String
   
   sTmp2 = GetTempPath
   sTmp = Space(Len(sTmp2) + 256)
   Call GetTempFileNameA(sTmp2, App.EXEName, UNIQUE_NAME, sTmp)
   GetTempFileName = Left$(sTmp, InStr(sTmp, Chr$(0)) - 1)

End Function

Public Function GetTempPath() As String
   ' *** Returns the path to the temp directory.
     
   Dim sTmp       As String
   Dim i          As Integer
   
   i = GetTempPathA(0, "")
   sTmp = Space(i)
   
   Call GetTempPathA(i, sTmp)
   GetTempPath = AddBackslash(Left$(sTmp, i - 1))

End Function


Function FileReplaceString(sFileIn As String, sSearchFor As String, sReplaceWith As String) As Boolean
   ' *** Searches in sFile file for sSearchFor
   ' *** and replaces it with sReplaceWith.

   Dim nFileIn    As Integer
   Dim nFileOut   As Integer
   
   Dim sFileOut   As String
   
   Dim sTmp       As String
   Dim sText      As String
   
   Dim nMax       As Long
   Dim nCount     As Long
   
   On Error GoTo ERROR_FileReplaceString
   
   sFileOut = GetTempFileName()
   
   ' *** Get the maximum size
   nMax = FileLen(sFileIn)
   
   If (nMax > 32000) Then
      nCount = 32000
   Else
      nCount = nMax
      nMax = nMax - nCount
   End If
   
   ' *** Open the file to read all the text file
   nFileIn = FreeFile
   Open sFileIn For Input As #nFileIn
   
   ' *** Save as temporary
   nFileOut = FreeFile
   Open sFileOut For Output As #nFileOut
   
   sText = ""
   Do While EOF(nFileIn) = False
      sTmp = Input(nCount, #nFileIn)
      sText = ReplaceString(sTmp, sSearchFor, sReplaceWith)
      Write #nFileOut, , sText
     
      If (nMax > 32000) Then
         nCount = 32000
      Else
         nCount = nMax
         nMax = nMax - nCount
      End If
   
   Loop
   Close #nFileIn
   Close #nFileOut

   ' *** Copy the temporary to the original
   FileCopy sFileOut, sFileIn
   
   ' *** Delete the temporary file
   Kill sFileOut
   
   FileReplaceString = True
   Exit Function

ERROR_FileReplaceString:
   If (Len(sFileOut) > 0) Then Kill sFileOut
   
   FileReplaceString = False
   
   Exit Function

End Function

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses
Course of the Month9 days, 14 hours left to enroll

624 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question