替换所有子文件夹中所有csv的文本

时间:2014-07-30 07:04:03

标签: vba excel-vba csv dir excel

我有一个代码来替换文件夹中所有文件的文本。但我还需要替换所有子文件夹中的文本。我怎么了?

Sub ProcessFiles()
Dim Filename, Pathname As String
Dim wb As Workbook

Pathname = "C:\Users\pabitra.pradhan\Downloads\RATES\"
Filename = Dir(Pathname & "*.csv")
Do While Filename <> ""
    Set wb = Workbooks.Open(Pathname & Filename)
    DoWork wb
    wb.Close SaveChanges:=True
    Filename = Dir()
Loop
End Sub

Sub DoWork(wb As Workbook)
With wb
    .Worksheets(1).Select
    Cells.Replace What:="MDL04", Replacement:="MDL05", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False
End With
End Sub

1 个答案:

答案 0 :(得分:0)

你需要做同样的递归:

Sub ProcessFiles(myFolder As String)

Dim Filename, Pathname As String
Dim wb As Workbook

Filename = Dir(myFolder & "*.csv")
  Do While Filename <> ""
    Set wb = Workbooks.Open(myFolder & Filename)
    DoWork wb
    wb.Close SaveChanges:=True
    Filename = Dir()
 Loop

Dim FSfolder As Folder 

Set FSfolder = FS.GetFolder(myFolder ) 

For Each mySubFolder In FSfolder.SubFolders
    Call ProcessFiles(FSfolder.Path)
Next

End Sub