写一段VBA宏,需求将文件夹 ORG_FILES 里的文件复制新生成文件并按规则1分类汇总进新建的文件夹里,新建的文件夹放入NEW_FILES文件夹内. 规则1:文件名称前12位字符相同的文件,提取这12位字符,去除重复和排序放入ZTE DOC 文件表格的A列里,并提取这12个数字命名生成新的文件夹,并将前12位字符相同的文件放进对应的文件夹里. 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-08-04 22:25:26 浏览: 46
以下是满足您要求的VBA宏代码:
```
Sub CopyFiles()
Dim orgPath As String, newPath As String, docPath As String
Dim orgFolder As Object, newFolder As Object, docWorkbook As Workbook
Dim orgFile As Object, newFile As Object
Dim fileName As String, folderName As String, sheetName As String
Dim rowNum As Integer, i As Integer, j As Integer
Dim nameList() As String, uniqueList() As String
' 设置文件夹路径
orgPath = "C:\Users\DELL\Desktop\ZTE FILE\ORG_FILES\"
newPath = "C:\Users\DELL\Desktop\ZTE FILE\NEW_FILES\"
docPath = "C:\Users\DELL\Desktop\ZTE FILE\ZTE DOC.xlsx"
folderName = ""
' 创建ZTE DOC工作簿对象
Set docWorkbook = Workbooks.Open(docPath)
' 循环读取ORG_FILES文件夹内的文件
Set orgFolder = CreateObject("Scripting.FileSystemObject").GetFolder(orgPath)
For Each orgFile In orgFolder.Files
' 获取文件名及前12位字符
fileName = orgFile.Name
If Len(fileName) >= 12 Then
folderName = Left(fileName, 12)
End If
' 检查是否需要创建新文件夹
If folderName <> "" And folderName <> prevFolderName Then
' 创建新文件夹
folderName = Trim(folderName)
If Not CreateFolder(newPath, folderName) Then
MsgBox "创建文件夹失败!"
Exit Sub
End If
' 将文件夹名写入ZTE DOC文件表格
sheetName = "Sheet1"
With docWorkbook.Sheets(sheetName)
rowNum = .Range("A1").End(xlDown).Row
.Cells(rowNum + 1, "A").Value = folderName
' 去除重复和排序
nameList = .Range("A2:A" & rowNum + 1).Value
uniqueList = RemoveDuplicates(nameList)
.Range("A2:A" & rowNum + 1).ClearContents
For i = 1 To UBound(uniqueList)
.Cells(i + 1, "A").Value = uniqueList(i)
Next i
.Range("A2:A" & UBound(uniqueList) + 1).Sort key1:=.Range("A2"), order1:=xlAscending, Header:=xlNo
End With
prevFolderName = folderName
End If
' 将文件复制到新文件夹
Set newFolder = CreateObject("Scripting.FileSystemObject").GetFolder(newPath & folderName)
Set newFile = newFolder.Files.Add(fileName, True)
newFile.Delete
orgFile.Copy newFolder.Path & "\"
Next orgFile
docWorkbook.Close SaveChanges:=True
MsgBox "处理完成!"
End Sub
Function CreateFolder(path As String, folderName As String) As Boolean
' 检查文件夹是否存在
If Len(Dir(path & folderName, vbDirectory)) = 0 Then
' 创建新文件夹
On Error Resume Next
MkDir path & folderName
If Err.Number <> 0 Then
CreateFolder = False
Else
CreateFolder = True
End If
On Error GoTo 0
Else
CreateFolder = True
End If
End Function
Function RemoveDuplicates(arr() As String) As String()
' 去除重复项
Dim dict As Object, item As Variant, i As Long
Set dict = CreateObject("Scripting.Dictionary")
For i = LBound(arr, 1) To UBound(arr, 1)
dict(arr(i, 1)) = ""
Next i
ReDim arr2(1 To dict.Count)
i = 0
For Each item In dict.Keys
i = i + 1
arr2(i) = item
Next item
RemoveDuplicates = arr2
End Function
```
注意:在运行该宏之前,请确保已经在ZTE DOC.xlsx文件的Sheet1工作表中创建了名为“Sheet1”的工作表,并将第一行第一列的格子命名为“A”。