【问题标题】:Replace text in documents in subfolders vba替换子文件夹vba中文档中的文本
【发布时间】:2015-09-10 17:04:28
【问题描述】:

我发现这个线程与我的问题相同,但我已将代码复制到我的项目中,但它似乎不起作用。

VBA macro: replace text in word file in all sub folders

我正在单步执行代码,它到达第 32 行(在 colSubFolders 中的 For Each varItem 下),但随后它直接跳过查找/替换部分到代码末尾。是我的文件格式有问题吗?

编辑:此外,当我到达 ln 31 中的 varitem 时,“varitem”的值是文件夹的名称,而不是文件夹中单词文档的名称:我认为这就是问题所在。

Sub DoLangesNow()
Dim file
Dim path As String
Dim strFolder As String
Dim strSubFolder As String
Dim strFile As String
Dim colSubFolders As New Collection
Dim varItem As Variant

 ' Parent folder including trailing backslash
 'YOU MUST EDIT THIS.
     strFolder = "L:\Admin\Corporate Books\2015\2014 Consents macro\company Annual Consents"
     ' Loop through the subfolders and fill Collection object
     strSubFolder = Dir(strFolder & "*", vbDirectory)
     Do While Not strSubFolder = ""
         Select Case strSubFolder
             Case ".", ".."
                 ' Current folder or parent folder - ignore
             Case Else
                 ' Add to collection
                 colSubFolders.Add Item:=strSubFolder, Key:=strSubFolder
         End Select
         ' On to the next one
         strSubFolder = Dir
     Loop
     ' Loop through the collection
     For Each varItem In colSubFolders
         ' Loop through word docs in subfolder
         'YOU MUST EDIT THIS if you want to change the files extension
         strFile = Dir(strFolder & varItem & "\" & "*.doc")
         Do While strFile <> ""
         Set file = Documents.Open(FileName:=strFolder & _
                 varItem & "\" & strFile)

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    使用 CMD 将所有文件放入一个数组并使用它来代替 - 更快更简洁。

    Sub S_O()
    
    Dim fileArray As Variant
    
    fileArray = Filter(Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & strFolder & "\*.doc*"" /S /B /A:-D").StdOut.ReadAll, vbCrLf), ".")
    
    For Each fil In fileArray
        '//
        '// Insert your code for doing the replacements here
        '// e.g. Workbooks.Open(fil)
        '// ...
    Next
    
    End Sub
    

    【讨论】:

    • @S O 有一些我从未使用过的东西......我仍在学习 VBA。你能解释一下我将如何整合它吗?
    • 顶行在strFolder 给出的路径的所有文件夹/子文件夹中创建了一个包含所有.doc* 文件名的数组。然后您可以遍历这个数组(使用For Each 语法并针对该文件运行您需要的任何代码,例如Documents.Open(fil)
    • 所以这会将所选子文件夹中的所有文档放入即时箱中?我应该在程序结束时清除它吗?可能是这样的? Dim x As Long For x = 1 To 10 Debug.Print x Next Debug.Print Now Application.SendKeys "^g ^a {DEL}"
    • 我刚刚将Debug.Print 用于演示目的,您可以将该行替换为您计划为每个文件运行的实际代码。
    • 哦!这更有意义。非常感谢您的帮助
    猜你喜欢
    • 2013-05-30
    • 2013-10-11
    • 2023-03-27
    • 2011-02-09
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 2017-08-06
    • 2021-10-13
    相关资源
    最近更新 更多