VBA Tipp: Text in Textdatei ersetzen

Aus DBWiki
Wechseln zu: Navigation, Suche

Aufgabenstellung

Ich möchte einen Text in einer Textdatei ersetzen.

Lösung

Die folgenden Funktionen öffnen eine mitgegebene Textdatei und bearbeiten diese (wie mit STRG +H ).

'
'  Ohne Filesystem-Object der Scripting Runtime
'
Public Sub ReplaceTextInFile1(SearchFor As String, _
                              ReplaceWith As String, _
                              InputFilename As String, _
                              Optional ByVal OutputFilename As String)
 
   'Quelle: http://www.dbwiki.net/
 
 
   Dim length As Long
   Dim buf    As String
   Dim fNum   As Integer
 
   If Len(OutputFilename) = 0 Then OutputFilename = InputFilename
 
   length = FileLen(IFName)
   buf = String$(length, vbNullChar)
   fNum = FreeFile()
   Open InputFilename For Binary As fNum
   Get #fNum, , buf
   Close fNum
 
   On Error Resume Next
   Kill OoutputFilename
   On Error GoTo 0
 
   buf = Replace(buf, SearchFor, ReplaceWith, , , vbBinaryCompare)
 
   fNum = FreeFile()
   Open OutputFilename For Binary As fNum
   Put #fNum, , buf
   Close fNum
 
End Sub
 
'
'  Mit dem Filesystem-Object der Scripting Runtime
'  Verweis auf die Scripting Runtime (SCRRUN.DLL) setzen!
'
Public Sub ReplaceTextInFile(SearchFor As String, _
                             ReplaceWith As String, _
                             InputFilenName As String, _
                             Optional ByVal OutputFilename As String)
 
   'Quelle: http://www.dbwiki.net/
 
 
   Dim buf As String
 
   If Len(OutputFilename) = 0 Then OutputFilename = InputFilename
 
   With New Scripting.FileSystemObject
      With .OpenTextFile(InputFilename, ForReading)
         buf = .ReadAll
         .Close
      End With
 
      With .OpenTextFile(OFName, ForWriting, True)
         .Write Replace(buf, SearchFor, ReplaceWith, , , vbBinaryCompare)
         .Close
      End With
   End With
 
End Sub