excel - 使用 Excel VBA 重命名多个文件
问题描述
我正在使用这两个代码:
- Get_Files_Information:从文件夹中提取文件名以进行重命名
Option Explicit
Sub Get_Files_Information()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Set fo = fso.GetFolder(sh.Range("H1").Value)
Dim last_raw As Integer
For Each f In fo.Files
last_raw = sh.Range("A" & Application.Rows.Count).End(xlUp).Row + 1
sh.Range("A" & last_raw).Value = f.Name
Next
MsgBox "Done"
End Sub
- Rename_Files:这段代码是重命名文件
Sub Rename_Files()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Dim new_name As String
Set fo = fso.GetFolder(sh.Range("H1").Value)
For Each f In fo.Files
new_name = Application.VLookup(f.Name, sh.Range("A:B"), 2, 0)
f.Name = new_name
Next
MsgBox "Done"
End Sub
当 Get_Files_Information 获取文件名时,结果将带有文件扩展名。我想从文件名中排除文件扩展名,这样重命名就不会因为文件扩展名而卡住。
同样在执行重命名代码时我得到
键入不匹配运行时错误 13。
上new_name = Application.VLookup(f.Name, sh.Range("A:B"), 2, 0)
Excel 宏文件供参考。
https://drive.google.com/open?id=1Zivo3aIn-Id9XtgQu-qpOstL_j7eacjv
解决方案
试试下面的代码。它将检查是否Application.VLookup(f.Name, sh.Range("A:B"), 2, 0)
返回错误(可能是由返回错误的公式引起的,如#VALUE)
Sub Rename_Files()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Dim new_name As String
Set fo = fso.GetFolder(sh.Range("H1").Value)
For Each f In fo.Files
Dim vRes As Variant
vRes = Application.VLookup(f.Name, sh.Range("A:B"), 2, 0)
If IsError(vRes) Then
MsgBox "Cannot rename " & f.Name & " - " & CStr(vRes)
Else
new_name = vRes
f.Name = new_name
End If
Next
MsgBox "Done"
End Sub
推荐阅读
- javascript - 如何将控制台日志中的结果保存到数据库?
- spring - Spring Boot 返回字符串而不是视图
- python - 获取两个多边形相交区域的坐标(在 Python 中)
- python - 检测和打印条纹
- javascript - Javascript中的问号是什么?
- java - 验证和订购阈值列表,如俄罗斯娃娃
- windows - 是否有相当于 Windows“调用”命令的 macOS?
- r - 如何从 R 中的 h2o 模型绘制 AUCPR 曲线?
- ionic-framework - 如何修复 UIWebView 已弃用的 Ionic 4
- tcl - 在 Tcl 中使用字符串递增数组时如何修复预期的整数错误