批量创建文件夹和文件——excel VBA实现

[复制链接]
发表于 2026-1-24 11:40:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
当必要创建大量文件夹及文件时,可借助excel vba 实现,如下图:
 批量创建文件名为1-10的文件夹,每个文件夹内有个与文件名类似的txt文件,txt文件内的数字也跟文件名类似。

 

 

附代码:
  1. Sub CreateFoldersAndFiles()
  2.     Dim i As Integer
  3.     Dim folderPath As String
  4.     Dim filePath As String
  5.     Dim textFile As Integer
  6.    
  7.     ' 获取当前Excel文件所在的文件夹路径
  8.     folderPath = ThisWorkbook.Path & ""
  9.    
  10.     ' 循环创建10个文件夹和txt文件
  11.     For i = 1 To 10
  12.         ' 创建文件夹
  13.         MkDir folderPath & i
  14.         
  15.         ' 生成txt文件路径
  16.         filePath = folderPath & i & "" & i & ".txt"
  17.         
  18.         ' 创建并写入txt文件
  19.         textFile = FreeFile
  20.         Open filePath For Output As textFile
  21.         Print #textFile, i
  22.         Close textFile
  23.     Next i
  24.    
  25.     MsgBox "文件夹和文件创建完成!"
  26. End Sub
复制代码

aaa
  1. Sub RenameFilesInSubfolders()
  2. 'qq443440204版权所有
  3.     Dim folderPath As String
  4.     Dim subFolder As Object
  5.     Dim file As Object
  6.     Dim newFileName As String
  7.     Dim fileExtension As String
  8.     Dim fs As Object
  9.   On Error Resume Next
  10.     ' 设置主文件夹路径
  11.     folderPath = "D:\xxx" ' 请将此路径替换为你的实际路径
  12.   
  13.     ' 创建FileSystemObject
  14.     Set fs = CreateObject("Scripting.FileSystemObject")
  15.   
  16.     ' 获取主文件夹对象
  17.     Set mainFolder = fs.GetFolder(folderPath)
  18.   
  19.     ' 遍历主文件夹下的所有子文件夹
  20.     For Each subFolder In mainFolder.SubFolders
  21.         ' 遍历子文件夹下的所有文件
  22.         For Each file In subFolder.Files
  23.             ' 获取文件扩展名
  24.             fileExtension = fs.GetExtensionName(file.Path)
  25.               
  26.             ' 构建新的文件名(子文件夹名称 + 文件扩展名)
  27.             newFileName = subFolder.Name & "." & fileExtension
  28.               
  29.             ' 生成新的文件路径
  30.             newFilePath = fs.BuildPath(subFolder.Path, newFileName)
  31.               
  32.             ' 重命名文件
  33.             Name file.Path As newFilePath
  34.         Next file
  35.     Next subFolder
  36.   
  37.     ' 清理对象
  38.     Set fs = Nothing
  39.     Set mainFolder = Nothing
  40.   
  41.     MsgBox "文件重命名完成!443440204"
  42. End Sub
复制代码
 
代码代写,可点击下方接洽 ↓ 
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表