2012-02-02 35 views
1

我想實現一個查找和替換使用VBS腳本文件夾中的所有文件替換多個文件,這裏是我迄今爲止查找和VBS

Dim fso,folder,files,oldFileContents,newFileContents,FIND,REPLACE 

FIND = "textToBeReplaced" 
REPLACE = "localhost" 

Set fso = CreateObject("Scripting.FileSystemObject") 

Set folder = fso.GetFolder("HTML") 
Set files = folder.Files 

For each item In files 
    oldFileContents = GetFile(item.Path) 
    newFileContents = replace(oldFileContents,FIND,REPLACE,1,-1,1) 
    WriteFile FileName,newFileContents 
Next 

但是當我嘗試運行它我得到和錯誤,「類型不匹配:'GetFile'」,我做錯了什麼?

回答

1

oldFileContents = fso.GetFile(item.Path) 

fso.WriteFile FileName,newFileContents 

錯過了fso.編輯:按下面的討論,請注意這個答案只是爲了顯示在您的錯誤發生在。假設你的意圖是在你過去發生這個錯誤時進一步開發你的代碼,如果是這樣的話,我相信你已經看到Ekkehard爲他的答案提供了一些非常有用的指導。

+0

-1 - .GetFile()返回一個文件對象,而不是文件的內容 – 2012-02-02 21:45:22

+0

@ekkehard我只是簡單地說明爲什麼'GetFile'正在下降。這就是所有問題。之後它被用於什麼與我無關 – Skytunnel 2012-02-02 22:16:48

+0

對於「之後所用的東西與我無關」,並且在嘗試顯示.GetFile()的用法時忘記了Set,您應該得到另一個downvote 。 – 2012-02-02 22:25:10

3

問題應與代碼來解決,如:

' Constants Mr Gates forgot (but cf. vbTextCompare) 
    Const ForReading = 1 
    Const ForWriting = 2 
' Configuration constants 
    Const csFind  = "pdf" 
    Const csRepl  = "puf" 
' Dim & init for vars needed on *this* level 
    Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject") 
    Dim sTDir : sTDir = oFS.GetAbsolutePathName("..\data\test") 
    Dim oFile 
    For Each oFile In oFS.GetFolder(sTDir).Files 
     WScript.Echo "looking at", oFile.Name 
     ' Dim & init for vars needed on *this* level 
     Dim sContent : sContent = goFS.GetFile(oFile.Path) 
     ' For Skytunnels and other air-coders 
     WScript.Echo "content is not", sContent 
     ' you got oFile, so use it; no need for .GetFile() 
     sContent = oFile.OpenAsTextStream(ForReading).ReadAll() 
     WScript.Echo "qed! content is", sContent 
     ' Replace(expression, find, replacewith[, start[, count[, compare]]]) 
     ' don't use magic numbers; vbTextCompare is even pre-defined 
     sContent = Replace(sContent, csFind, csRepl, 1, -1, vbTextCompare) 
     WScript.Echo "new content", sContent 
     oFile.OpenAsTextStream(ForWriting).Write sContent 
     sContent = oFile.OpenAsTextStream(ForReading).ReadAll() 
     WScript.Echo "new content straight from file", sContent 
     WScript.Echo "------------------" 
    Next 

輸出:

... 
------------------ 
looking at 0000000000.20120302.pdf 
content is not E:\trials\SoTrials\answers\9117277\data\test\0000000000.20120302.pdf 
qed! content is This is the content of 0000000000.20120302.pdf 

new content This is the content of 0000000000.20120302.puf 

new content straight from file This is the content of 0000000000.20120302.puf 

要點:

  1. 不要用點心全瓦爾前所未有 - 腳本頂部的已用線
  2. 避免創建不必要的變量(文件夾,文件,*內容),使用 的瓦爾你有正確的(項目== OFILE)
  3. .GetFile()返回一個文件對象,而不是文件的內容