问题出现时机:在遍历文件夹中所有的xlsx文件时,发现文件名中有许多空格,单独处理一个文件删除空格符,处理完成后再加回去很麻烦。
Sub 修改公式()
Dim folderPath As String
Dim fileName As String
Dim wb As Workbook
Dim ws As Worksheet
' 设置文件夹路径
folderPath = "C:\Users\XXX\Documents\" ' 替换文件夹路径
' 检查文件夹路径是否存在
If Dir(folderPath, vbDirectory) = "" Then
MsgBox "指定的文件夹路径不存在。", vbExclamation
Exit Sub
End If
' 循环遍历文件夹中的所有xlsx文件
fileName = Dir(folderPath & "\" & "*.xlsx")
Do While fileName <> ""
' 打开工作簿
Set wb = Workbooks.Open(folderPath & "\" & fileName)
' 如果成功打开工作簿
If Not wb Is Nothing Then
' 获取Output sheet页
Set ws = wb.Sheets("Output")
If Not ws Is Nothing Then
If ws.ProtectContents Then
' 解除保护
ws.Unprotect Password:="1234"
End If
' 修改F1单元格的公式
ws.Range("F1").Formula = "***" ' 替换新公式
Else
MsgBox "未找到Output sheet页。", vbExclamation
End If
' 锁定工作表
ws.Protect Password:="1234"
ws.Protect
' 保存并关闭工作簿
wb.Close SaveChanges:=True
End If
' 继续处理下一个文件
fileName = Dir
Loop
MsgBox "完成修改公式。", vbInformation
End Sub
解决方式:考虑创建文件系统对象的方式获取当前路径下的文件名。
处理方式:
Sub 修改公式()
Dim folderPath As String
Dim fileName As String
Dim wb As Workbook
Dim ws As Worksheet
' 设置文件夹路径
folderPath = "C:\Users\xxx\Documents\" ' 替换文件夹路径
' 检查文件夹路径是否存在
If Dir(folderPath, vbDirectory) = "" Then
MsgBox "指定的文件夹路径不存在。", vbExclamation
Exit Sub
End If
' 创建文件系统对象
Set objFSO = CreateObject("Scripting.FileSystemObject")
' 获取文件夹对象
Set objFolder = objFSO.GetFolder(folderPath)
' 循环遍历文件夹中的所有xlsx文件
For Each objFile In objFolder.Files
' 检查文件扩展名是否为xlsx
If objFSO.GetExtensionName(objFile.Path) = "xlsx" Then
' 打开工作簿
Set wb = Workbooks.Open(objFile.Path)
' 如果成功打开工作簿
If Not wb Is Nothing Then
' 获取Output sheet页
Set ws = wb.Sheets("Output")
If Not ws Is Nothing Then
If ws.ProtectContents Then
' 解除保护
ws.Unprotect Password:="1234"
End If
' 修改F1单元格的公式
ws.Range("F1").Formula = "xxx" ' 替换新公式
Else
MsgBox "未找到Output sheet页。", vbExclamation
End If
' 锁定工作表
ws.Protect Password:="1234"
ws.Protect
' 保存并关闭工作簿
wb.Close SaveChanges:=True
End If
End If
Next objFile
MsgBox "完成修改公式。", vbInformation
End Sub