前面小编由于工作需要,需要修改几百个文件名,如果一个一个的点击修改,那就需要费好多时间了,幸好现在是AI时代,因此小编就在想,如果把我们的需求告诉AI,然后AI编写代码,能不能实现呢?需要的这个插件的小伙伴拖到文章最下面有免费获取方法
想到这里打开AI网站,输入如下提示,然后他就会编写自动输出代码了
然后我们就得到如下代码
Sub批量提取文件名()
Dim folderPath As String
Dim fileName As String
Dim i As Long
'设置文件夹路径(弹窗选择)
folderPath = GetFolderPath("请选择文件夹:")
If folderPath = "" Then Exit Sub
'清空表格数据(从第2行开始)
Cells.ClearContents
'写入标题
Range("A1").Value = "原文件名"
Range("B1").Value = "新文件名"
'使用Dir函数遍历文件夹中的文件
i = 2
fileName = Dir(folderPath & "*.*") '获取第一个文件名
Do While fileName <> ""
Cells(i, 1).Value = fileName '写入文件名到A列
i = i + 1
fileName = Dir '获取下一个文件名
Loop
MsgBox "文件名提取完成!"
End Sub
Sub批量修改文件名()
Dim folderPath As String
Dim oldName As String
Dim newName As String
Dim i As Long
'设置文件夹路径
folderPath = GetFolderPath("请选择文件夹:")
If folderPath = "" Then Exit Sub
'从A2和B2开始读取数据
i = 2
Do While Cells(i, 1).Value <> ""
'构造完整路径
oldName = folderPath & Cells(i, 1).Value
newName = folderPath & Cells(i, 2).Value
'检查文件是否存在
If Dir(oldName) = "" Then
MsgBox "文件不存在:" & oldName, vbExclamation
Exit Sub
End If
'检查新文件名是否为空
If newName = "" Then
MsgBox "新文件名不能为空!", vbExclamation
Exit Sub
End If
'重命名文件
Name oldName As newName
i = i + 1
Loop
MsgBox "文件名修改完成!"
End Sub
'弹窗选择文件夹
Function GetFolderPath(prompt As String) As String
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
fd.Title = prompt
If fd.Show = -1 Then
GetFolderPath = fd.SelectedItems(1) & "\"
Else
GetFolderPath = ""
End If
End Function
然后我们把他复制进excel里面,然后能正常运行,它主要是实现2个功能,一个是批量提取文件名,一个是批量修改文件名
点击运行后我们发现已经帮我们批量修改文件了,这就节省了我们很多的时间
领取专属 10元无门槛券
私享最新 技术干货