vbscript替换文本 - 一个工作两个打破整个事情

时间:2009-05-20 20:24:40

标签: vbscript

我希望此脚本替换同一文本文件中的两个值而不是一个。但是,如果我取消注释第12行,它会破坏脚本。我是否必须将其转换为循环,还是可以进行多次替换?

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 个答案:

答案 0 :(得分:6)

我想你会想要对第一个返回的字符串进行第二次替换:

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

否则您将失去第一个替换,并且只有第二个替换将出现在结果中。

答案 1 :(得分:0)

我确信我的if语句对那些真正的编码人员来说是丑陋的,但这就是我如何让它工作

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

答案 2 :(得分:0)

嗯..很容易.. Bueno ni tanto ..我试图这样做一段时间。我找到了答案:

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)
 strNewText2 = Replace(strNewText, "***Winkey***", strPoductkey)    '

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

坦克斯,格拉西亚斯。 JoséVilla来自墨西哥锡那罗亚州Culiacán

答案 3 :(得分:0)

试试这个:

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 

按照您的方式进行操作,您使用原始的未使用的文本两次,在第二次替换时覆盖第一次替换。