You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel更新后VBA失效,需遍历文件检查指定单元格并重命名符合条件文件

适配需求的精简VBA代码

以下代码完全移除原版本冗余逻辑,仅实现指定核心功能,兼容高版本Excel:

Sub 标记待删除文件()
    Dim folderPath As String
    Dim filename As String
    Dim wb As Workbook
    Dim targetVal As String
    
    ' 目标文件夹路径,可根据实际使用场景修改
    folderPath = "C:\Users\" & Environ$("Username") & "\Desktop\Process Production\"
    If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' 遍历目录下所有xlsx文件
    filename = Dir(folderPath & "*.xlsx")
    Do While filename <> ""
        ' 跳过代码所在的工作簿避免报错
        If filename <> ThisWorkbook.Name Then
            Set wb = Workbooks.Open(folderPath & filename, ReadOnly:=False)
            
            ' 错误捕获:跳过不存在Process Summary工作表的文件
            On Error Resume Next
            targetVal = vbNullString
            targetVal = VBA.Format(wb.Sheets("Process Summary").Range("D3").Value, "0.00%")
            On Error GoTo 0
            
            ' 匹配到0.00%则重命名为待删除标识
            If targetVal = "0.00%" Then
                wb.Close SaveChanges:=False
                ' 重命名规则可自行调整,当前为添加「待删除_」前缀
                Name folderPath & filename As folderPath & "待删除_" & filename
            Else
                wb.Close SaveChanges:=False
            End If
        End If
        filename = Dir
    Loop
    
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    MsgBox "文件处理完成"
End Sub
代码说明
  • 自动适配当前用户桌面的Process Production目录,可手动修改folderPath变量调整目标路径
  • 自带错误捕获机制,遇到无指定工作表、文件被占用等异常情况不会中断运行
  • 全程不修改原文件内部内容,仅对符合条件的文件做重命名操作,避免误改数据
  • 重命名规则可根据使用习惯调整,只需修改Name语句后半段的命名格式即可

内容的提问来源于stack exchange,提问作者Cassy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 01:27:03