写一个VBA宏,应用将ORG_FILES里的文件复制生成新文件放入NEW_FILES文件夹里,并把这些文件按规则重命名和分类汇总至对应的新建文件夹里; 重命名的规则请参考ZTE DOC工作表里A列和B列的映射关系,C列和D列的映射关系; 新建文件夹的规则参考A列格子里的信息 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-04 11:28:12 浏览: 92
复制目录下Execl文件sheet1表到新文件vba
好的,以下是VBA宏的代码:
```
Sub CopyAndRenameFiles()
Dim orgFolder As String, newFolder As String, docPath As String
Dim orgFiles As Object, orgFile As Variant
Dim newName As String, newFolderPath As String
Dim ws As Worksheet, i As Long, lastRow As Long
'设置文件夹路径和文档路径
orgFolder = "C:\Users\DELL\Desktop\ZTE FILE\ORG_FILES\"
newFolder = "C:\Users\DELL\Desktop\ZTE FILE\NEW_FILES\"
docPath = "C:\Users\DELL\Desktop\ZTE FILE\ZTE DOC.xlsx"
'打开ZTE DOC工作表
Set ws = Workbooks.Open(Filename:=docPath).Sheets("Sheet1")
'获取ORG_FILES文件夹下所有文件
Set orgFiles = CreateObject("Scripting.FileSystemObject").GetFolder(orgFolder).Files
'遍历所有文件
For Each orgFile In orgFiles
'获取新文件名和新文件夹路径
newName = GetNewName(orgFile.Name, ws)
newFolderPath = GetNewFolderPath(newName, ws, newFolder)
'复制文件到新文件夹
FileCopy orgFolder & orgFile.Name, newFolderPath & newName
Next orgFile
'关闭ZTE DOC工作表
ws.Parent.Close
'通知完成
MsgBox "操作完成!"
End Sub
Function GetNewName(ByVal orgName As String, ByVal ws As Worksheet) As String
Dim i As Long, lastRow As Long
'获取映射关系表最后一行
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
'遍历映射关系表
For i = 2 To lastRow
'匹配A列和B列
If InStr(orgName, ws.Cells(i, 1).Value) > 0 Then
GetNewName = Replace(orgName, ws.Cells(i, 1).Value, ws.Cells(i, 2).Value)
Exit Function
End If
Next i
'匹配不到就返回原文件名
GetNewName = orgName
End Function
Function GetNewFolderPath(ByVal newName As String, ByVal ws As Worksheet, ByVal newFolder As String) As String
Dim i As Long, lastRow As Long
Dim folderName As String
'获取映射关系表最后一行
lastRow = ws.Cells(ws.Rows.Count, 3).End(xlUp).Row
'遍历映射关系表
For i = 2 To lastRow
'匹配C列和D列
If InStr(newName, ws.Cells(i, 3).Value) > 0 Then
folderName = ws.Cells(i, 4).Value
Exit For
End If
Next i
'创建新文件夹
If folderName <> "" Then
If Len(Dir(newFolder & folderName, vbDirectory)) = 0 Then
MkDir newFolder & folderName
End If
GetNewFolderPath = newFolder & folderName & "\"
Else
GetNewFolderPath = newFolder
End If
End Function
```
运行这个宏之前,请确保已经在C:\Users\DELL\Desktop\ZTE FILE下创建了ORG_FILES和NEW_FILES两个文件夹,并且在C:\Users\DELL\Desktop\ZTE FILE下已经有ZTE DOC.xlsx文件。
这个宏会遍历ORG_FILES文件夹下的所有文件,根据文件名和ZTE DOC工作表里的映射关系,生成新的文件名和新的文件夹路径,然后把文件复制到对应的新文件夹里,并按照规则重命名。如果新文件夹不存在,则会自动创建。
阅读全文