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 Function ReplaceTextInFile1(ByVal Src As String, ByVal Repl As String, _
  ByVal IFName As String, Optional ByVal OFName As String)
Dim L As Long, S As String, FChan As Integer
  L = FileLen(IFName)
  S = String(L, 0)
  FChan = FreeFile()
  Open IFName For Binary As FChan
  Get FChan, , S
  Close FChan
  If OFName = "" Then OFName = IFName
  On Error Resume Next
  Kill OFName
  On Error GoTo 0
  S = Replace(S, Src, Repl)
  Open OFName For Binary As FChan
  Put FChan, , S
  Close FChan
End Function
 
'
'  Mit dem Filesystem-Object der Scripting Runtime
'  Verweis auf die Scripting Runtime (SCRRUN.DLL) setzen!
'
Public Function ReplaceTextInFile(ByVal Src As String, ByVal Repl As String, _
  ByVal IFName As String, Optional ByVal OFName As String)
Dim FSO As New Scripting.FileSystemObject
Dim Strm As Scripting.TextStream, S As String
  Set Strm = FSO.OpenTextFile(IFName, ForReading)
  S = Strm.ReadAll
  Strm.Close
  If OFName = "" Then OFName = IFName
  Set Strm = FSO.OpenTextFile(OFName, ForWriting, True)
  Strm.Write Replace(S, Src, Repl)
  Strm.Close
  Set FSO = Nothing
End Function