写一段VBA宏,分析将文件夹 ORG_FILES里的文件名字里带有DA前缀和10位数字的后缀,带有DZ前缀和10位数字的后缀,,带有MP前缀和10为数字的文件,把文件名中含2位前缀加10位数字后缀完全 一致文件复制生成新的文件放到NEW_FILES下新建的文件夹里,新建的文件夹用这相同的2位前缀和10位数字后缀命名. 这些新建的文件夹名字排序放入ZTE DOC这个表格的A1下面的格子里. ORG_FILES 文件夹位置:C:\Users\DELL\Desktop\ZTE FILE\ORG_FILES NEW_FILES文件夹位置:C:\Users\DELL\Desktop\ZTE FILE\NEW_FILES ZTE DOC文件夹位置:C:\Users\DELL\Desktop\ZTE FILE
时间: 2023-07-21 15:20:05 浏览: 70
Excel-VBA宏编程实例源代码-确定带完整目录的文件夹中是否有指定文件.zip
好的,这是您要求的 VBA 代码,可以实现您的需求:
```
Sub CopyFiles()
'设置路径和文件名前缀
Dim orgPath As String, newPath As String
Dim daPrefix As String, dzPrefix As String, mpPrefix As String
orgPath = "C:\Users\DELL\Desktop\ZTE FILE\ORG_FILES\"
newPath = "C:\Users\DELL\Desktop\ZTE FILE\NEW_FILES\"
daPrefix = "DA"
dzPrefix = "DZ"
mpPrefix = "MP"
'设置 Excel 表格路径和工作表名字
Dim wb As Workbook, ws As Worksheet
Dim docPath As String, docName As String, cellAddress As String
docPath = "C:\Users\DELL\Desktop\ZTE FILE\ZTE DOC.xlsx"
docName = "Sheet1"
cellAddress = "A1"
'打开 Excel 表格
Set wb = Workbooks.Open(docPath)
Set ws = wb.Sheets(docName)
'定义变量
Dim daFiles As Variant, dzFiles As Variant, mpFiles As Variant
Dim daFolder As String, dzFolder As String, mpFolder As String
Dim daNewFolder As String, dzNewFolder As String, mpNewFolder As String
Dim i As Long, j As Long, k As Long
'查找符合条件的文件
daFiles = Dir(orgPath & daPrefix & "*.xlsx")
dzFiles = Dir(orgPath & dzPrefix & "*.xlsx")
mpFiles = Dir(orgPath & mpPrefix & "*.xlsx")
'创建新文件夹并复制文件
Do While daFiles <> ""
If Len(daFiles) = 12 Then
daFolder = Left(daFiles, 2) & Mid(daFiles, 3, 10)
daNewFolder = newPath & daFolder
If Not FolderExists(daNewFolder) Then
MkDir daNewFolder
ws.Range(cellAddress).Offset(i, 0).Value = daFolder
i = i + 1
End If
FileCopy orgPath & daFiles, daNewFolder & "\" & daFiles
End If
daFiles = Dir
Loop
Do While dzFiles <> ""
If Len(dzFiles) = 12 Then
dzFolder = Left(dzFiles, 2) & Mid(dzFiles, 3, 10)
dzNewFolder = newPath & dzFolder
If Not FolderExists(dzNewFolder) Then
MkDir dzNewFolder
ws.Range(cellAddress).Offset(i, 0).Value = dzFolder
i = i + 1
End If
FileCopy orgPath & dzFiles, dzNewFolder & "\" & dzFiles
End If
dzFiles = Dir
Loop
Do While mpFiles <> ""
If Len(mpFiles) = 12 Then
mpFolder = Left(mpFiles, 2) & Mid(mpFiles, 3, 10)
mpNewFolder = newPath & mpFolder
If Not FolderExists(mpNewFolder) Then
MkDir mpNewFolder
ws.Range(cellAddress).Offset(i, 0).Value = mpFolder
i = i + 1
End If
FileCopy orgPath & mpFiles, mpNewFolder & "\" & mpFiles
End If
mpFiles = Dir
Loop
'保存并关闭 Excel 表格
wb.Save
wb.Close
End Sub
Function FolderExists(ByVal folderPath As String) As Boolean
'检查文件夹是否存在
If Dir(folderPath, vbDirectory) = "" Then
FolderExists = False
Else
FolderExists = True
End If
End Function
```
请将代码复制到 VBA 编辑器中,并在执行代码之前,请务必备份您的数据。
阅读全文