tags:

views:

1210

answers:

3

I want this script to replace two values in the same text file instead of one. However, if I uncomment line 12, it breaks the script. Do I have to make this into a loop, or can I do multiple replaces?

Sub ReplaceTxt()
'Writes values we got earlier to our unattend file       '
Const ForReading = 1
Const ForWriting = 2

   Set objFSO = CreateObject("Scripting.FileSystemObject")
   Set objFile = objFSO.OpenTextFile(strSIFpath, ForReading)

   strText = objFile.ReadAll
   objFile.Close
   strNewText = Replace(strText, "***COMPNAME***", strCompname)
 '  strNewText = Replace(strText, "***Winkey***", strPoductkey)    '

   Set objFile = objFSO.OpenTextFile("C:\$WIN_NT$.~BT\winnt.sif", ForWriting)
   objFile.WriteLine strNewText
   objFile.Close
End Sub
+4  A: 

I think you will want to do the second replace on the string returned by the first one:

strNewText = Replace(strText, "***COMPNAME***", strCompname)
strNewText = Replace(strNewText , "***Winkey***", strPoductkey)

Otherwise you will lose the first replace, and only the second one will appear in the result.

Fredrik Mörk
A: 

Try this:

Sub ReplaceTxt() 'Writes values we got earlier to our unattend file' 
  Const ForReading = 1
  Const ForWriting = 2

  Set objFSO = CreateObject("Scripting.FileSystemObject")
  Set objFile = objFSO.OpenTextFile(strSIFpath, ForReading)

  strText = objFile.ReadAll
  objFile.Close

  strText = Replace(strText, "COMPNAME", strCompname)
  strText = Replace(strText, "Winkey", strPoductkey)

  Set objFile = objFSO.OpenTextFile("C:\$WIN_NT$.~BT\winnt.sif", ForWriting)
  objFile.WriteLine strText
  objFile.Close
End Sub

By doing it the way you were, you were using the original, unused text twice, overwriting the first replace when you did the second.

AnonJr
objFile.WriteLine strNewText should be strText
AnthonyWJones
Thanks - lack of coffee moment. :D
AnonJr
Both of these do the same thing, first replace works, second is blank.
Travis
Odd as I have similar code working in a different application...
AnonJr
A: 

I'm sure my if statement is ugly to the real coders out there, but here's how I got it to work

Sub ReplaceTxt() 'Writes values we got earlier to our unattend file' 
  Const ForReading = 1
  Const ForWriting = 2
  counter = 1

  For Each searchterm In Array("COMPNAME", "Winkey")
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  Set objFile = objFSO.OpenTextFile(strSIFpath, ForReading)

  strText = objFile.ReadAll
  objFile.Close

  If counter < 2 Then
     strText = Replace(strText, searchterm, strCompname)
  Else
     strText = Replace(strText, searchterm, strProductKey)
  End If

  Set objFile = objFSO.OpenTextFile("C:\$WIN_NT$.~BT\winnt.sif", ForWriting)
  objFile.WriteLine strText
  objFile.Close
  counter = counter + 1
  Next
End Sub
Travis