批量复制指定文件夹——EXCEL VBA 实现

工作中往往需要复制特定文件夹,例如,一个文件夹中有100个文件夹,我只需要复制其中50个文件夹,这50个文件夹的名字放入excel表中第一列,从第二行开始(注意:第一行的表头不能覆盖),运行宏即可一键完成。如下图:

上图可知,我们已成功复制。

附部分代码如下:

vbnet 复制代码
Sub CopySubFoldersToNewFolder()
'版权所有yngqq:443440204@2024年9月9日15:11:57
    Dim ws As Worksheet
    Dim folderName As String
    Dim sourcePath As String
    Dim destPath As String
    Dim rowNum As Long
    Dim lastRow As Long
    Dim fso As Object
    Dim missingFolders As String
    Dim parentFolderPath As String
    Dim newDesktopFolder As String
    
    ' 定义工作表
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    ' 文件系统对象
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    ' 已知的父文件夹路径(请根据实际情况修改)
    parentFolderPath = ThisWorkbook.Path & "\"    ' 修改为实际的父文件夹路径
    
    ' 定义桌面路径,并创建一个新的文件夹 "CopiedFolders"
    newf = parentFolderPath & "复制到此文件夹"
    On Error GoTo 2000
2000:
inum = imum + 1
    If Not fso.FolderExists(newf) Then
        MkDir newf
        
    Else
   
    newf = newf & inum
    GoTo 2000
    End If
   On Error GoTo 0
    newDesktopFolder = newf & "\"
    ' 如果目标文件夹不存在,则创建
    If Not fso.FolderExists(newDesktopFolder) Then
        fso.CreateFolder newDesktopFolder
    End If
    
    ' 获取最后一行
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    
    ' 初始化缺失文件夹的列表
    missingFolders = ""
    
    ' 遍历Excel中的每个文件夹名
    For rowNum = 2 To lastRow
        folderName = ws.Cells(rowNum, 1).Value
        sourcePath = parentFolderPath & folderName
        destPath = newDesktopFolder & folderName
        
        ' 检查源文件夹是否存在
        If fso.FolderExists(sourcePath) Then
            ' 如果目标文件夹不存在,则复制
            If Not fso.FolderExists(destPath) Then
                fso.CopyFolder sourcePath, destPath
                ws.Cells(rowNum, 2).Value = "复制成功"
            Else
                ws.Cells(rowNum, 2).Value = "目标文件夹已存在"
            End If
        Else
            ws.Cells(rowNum, 2).Value = "源文件夹不存在"
            ' 记录不存在的文件夹名
            missingFolders = missingFolders & folderName & vbCrLf
        End If
    Next rowNum
    
    ' 释放对象
    Set fso = Nothing
    
    ' 如果有缺失的文件夹,弹出提示框
    If missingFolders <> "" Then
        MsgBox "以下文件夹不存在:" & vbCrLf & missingFolders
    Else
        MsgBox "文件夹复制完成!路径为:" & vbCrLf & newf & vbCrLf & "qq:443440204.vba代码代写", , "qq:443440204.vba代码代写"
    End If
End Sub

代码代写,可点击下方联系 ↓

相关推荐
LAM LAB4 天前
【VBA】Excel指定单元格范围内字体设置样式,处理导出课表单元格
excel·vba
在这habit之下4 天前
Keepalived学习总结
excel
Youngchatgpt5 天前
如何在 Excel 中使用 ChatGPT:自动化任务和编写公式
人工智能·chatgpt·自动化·excel
开开心心就好5 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
D_C_tyu5 天前
Vue3 + Element Plus | el-table 多级表头表格导出 Excel(含合并单元格、单元格居中)第二版
vue.js·elementui·excel
骆驼爱记录5 天前
WPS页码设置:第X页共Y-1页
自动化·word·excel·wps·新人首发
Cxiaomu6 天前
Python 文件解析: Excel / Word / PDF 的解析、处理、预览与下载
python·word·excel
2501_930707786 天前
如何使用C#代码从 PDF 中提取表格并另存为Excel文件
pdf·excel
pacong6 天前
B生所学EXCEL
人工智能·excel