对文件夹和所有子文件夹VBA中的所有word文件执行任务

时间:2017-07-06 19:18:01

标签: vba word-vba

我对这个网站很新,这是我的第一篇文章。开始了: 我正在VBA上编写一个相当简单的代码,用于替换某个特定的字符链。我有那个部分想通了,但是我想在包含子文件夹的大文件夹中的所有文件上操作该代码....我之前看到过类似的问题,但它对我不起作用因为我试图在代码中输入“ If ”以验证文件是word文件,如果是,则调用对文件执行所需任务的操作(secondSubRoutine) 。如果有人能告诉我为什么它无法找到单词文件,那将非常有用!

Aurelion。

Sub domino()

Dim FileSystem As Object
Dim HostFolder As String

HostFolder = "C:\CLIENTS"

Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
End Sub
Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files

        If File.Name = "*.docx" Then

             Documents.Open FileName:=File

             Call secondSubRoutine

             ActiveDocument.Save
             ActiveDocument.Close

        ElseIf File.Name = "*.doc" Then


            Documents.Open FileName:=path & File

            Call secondSubRoutine

            ActiveDocument.Save
            ActiveDocument.Close

        End If

    Next

End Sub

1 个答案:

答案 0 :(得分:1)

试试这个:

For Each File In Folder.Files
    If Right(File.Name, 5) = ".docx" Or Right(File.Name, 4) = ".doc" Then

         Documents.Open FileName:=File.Path

         Call secondSubRoutine

         With ActiveDocument
            .Save
            .Close
        End With
    End If
Next