简体   繁体   English

如何循环遍历文件夹 A 的子文件夹以获取每个子文件夹中的文件名并使用 VBA 从文件夹 B 复制其他同名文件

[英]How to loop through sub folders of folder A to get file name in each subfolder and copy other file with same name from folder B using VBA

There is folder A which contains multiple subfolders like A1,A2, A3 etc which every subfolder has mostly one sometimes 2 word files with the name(eg file_a1) in it.文件夹 A 包含多个子文件夹,如 A1、A2、A3 等,每个子文件夹大多有一个有时是 2 个单词的文件,其中包含名称(例如 file_a1)。 Then, there is other folder B (not a subfolder of A) which contains multiple word files with standard similar (file_a1_XZ) names.然后,还有另一个文件夹 B(不是 A 的子文件夹),其中包含多个具有标准相似 (file_a1_XZ) 名称的单词文件。 I want to loop in subfolders of A and copy word files from B to respective sub folder eg A1我想在 A 的子文件夹中循环并将 word 文件从 B 复制到相应的子文件夹,例如 A1

File Structure:文件结构:

Parent Folder
|
|
 ----Parent B
     |
     |
      --- B
          |
           -file_a1_XZ
           -file_a2_XZ
 ----Parent A
     |
     |
      --- A
          |
          |
           -- A1
              |
               -file_a1
           -- A2
              |
               -file_a2

Move Files to Specific Folders Using Dir使用Dir将文件移动到特定文件夹

  • Moves files from B to subfolders of A ie the filenames contain the names of the subfolders.将文件从B移动到A的子文件夹,即文件名包含子文件夹的名称。
Option Explicit

Sub MoveFiles()
    
    Const sFolderPath As String = "C:\Test\T2022\71752347\B\"
    Const dFolderPath As String = "C:\Test\T2022\71752347\A\"
    Const sExtensionPattern As String = ".doc*"
    
    Dim dFolderName As String: dFolderName = Dir(dFolderPath, vbDirectory)
    
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    
    Do Until Len(dFolderName) = 0
        If dFolderName <> "." And dFolderName <> ".." Then
            dict(dFolderName) = Empty
        End If
        dFolderName = Dir
    Loop
    
    Dim Key As Variant
    Dim sFileName As String
    Dim fCount As Long
    
    For Each Key In dict.Keys
        
        sFileName = Dir(sFolderPath & "*" & Key & "*" & sExtensionPattern)
        
        Do Until Len(sFileName) = 0
            fCount = fCount + 1
            FileCopy sFolderPath & sFileName, _
                dFolderPath & Key & "\" & sFileName
            Kill sFolderPath & sFileName
            sFileName = Dir
        Loop
    
    Next

    MsgBox "Files moved: " & fCount, vbInformation

End Sub
  • If the files in B are in various subfolders, use the following.如果 B 中的文件在各个子文件夹中,请使用以下内容。
Sub MoveFiles()
    
    Const sFolderPath As String = "C:\Test\T2022\71752347\B\"
    Const dFolderPath As String = "C:\Test\T2022\71752347\A\"
    Const sExtensionPattern As String = ".doc*"
    
    Dim dFolderName As String: dFolderName = Dir(dFolderPath, vbDirectory)
    
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    
    Do Until Len(dFolderName) = 0
        If dFolderName <> "." And dFolderName <> ".." Then
            dict(dFolderName) = Empty
        End If
        dFolderName = Dir
    Loop
    
    Dim sFilePaths() As String
    Dim sFilePath As String
    Dim dFilePath As String
    Dim Key As Variant
    Dim f As Long
    Dim fCount As Long
    
    For Each Key In dict.Keys
        sFilePaths = ArrFilePaths(sFolderPath, _
            "*" & Key & "*" & sExtensionPattern)
        For f = 0 To UBound(sFilePaths)
            fCount = fCount + 1
            sFilePath = sFilePaths(f)
            dFilePath = dFolderPath & Key & "\" & Right(sFilePath, _
                Len(sFilePath) - InStrRev(sFilePath, "\"))
            FileCopy sFilePath, dFilePath
            Kill sFilePath
        Next f
    Next Key
        
    MsgBox "Files moved: " & fCount, vbInformation

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the file paths of the files in a folder
'               in a zero-based string array.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function ArrFilePaths( _
    ByVal FolderPath As String, _
    Optional ByVal FilePattern As String = "*.*", _
    Optional ByVal DirSwitches As String = "/s/b/a-d") _
As String()
    Const ProcName As String = "ArrFilePaths"
    On Error GoTo ClearError
    
    ' Ensuring that a string array is passed if an error occurs.
    ArrFilePaths = Split("") ' LB = 0 , UB = -1
   
    Dim pSep As String: pSep = Application.PathSeparator
    If Right(FolderPath, 1) <> pSep Then FolderPath = FolderPath & pSep
    Dim ExecString As String ' '%comspec%' or 'cmd.exe' ?
    ExecString = "%comspec% /c Dir """ _
        & FolderPath & FilePattern & """ " & DirSwitches
    Dim Arr() As String: Arr = Split(CreateObject("WScript.Shell") _
        .Exec(ExecString).StdOut.ReadAll, vbCrLf)
    If UBound(Arr) > 0 Then
        ReDim Preserve Arr(0 To UBound(Arr) - 1)
    End If
    ArrFilePaths = Arr

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果找到文件复制到vba宏中的另一个文件夹,请使用文件名在文件夹和子文件夹中搜索文件 - Search for a file in folders and sub folders using file name if found copy to another folder in vba macros 如何使用excel VBA遍历众多子文件夹并查找单元格值是否与文件夹名称匹配? - How to loop through numerous sub folders and find if a cell value matches a folder name using excel VBA? Excel VBA:将excel列从一个文件复制到相同名称的另一个文件(在不同文件夹中) - Excel VBA: copy excel columns from one file to other file (in different folder) of same name 使用文件夹中的文件名重命名子文件夹文件夹名称-VBA - Rename Subfolder folder name with File name inside the folder - vba 嵌套循环-VBA-复制工作表名称与特定文件夹中的文件名匹配的每个工作表 - Nested Loop- VBA- Copy each worksheet where the worksheet name matches file name in specific folder 从文件夹和子文件夹中搜索文件名(如果存在或不存在) - Search file name from folder and Subfolder if Exist or not 使用 VBA 重命名子文件夹上的文件(什么名字)? - Rename file ( what ever name ) on sub folder by using VBA? 如果已有同名文件,如何将文件复制到文件夹? - How to copy a file to a folder if there is already a file with the same name? Excel VBA-从静态文件夹名称复制文件,然后粘贴到ActiveCell中找到的文件夹名称中 - Excel VBA - copy a file from a static folder name and paste into a folder name found in an ActiveCell Excel vba:将文件从一个文件夹同时复制到多个文件夹 - Excel vba: copy file from one folder to many folders simultaneously
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM