VBA宏批量保护Excel文件工作表

选择目录,设置自定义密码,可对该目录以及其中子目录添加保护:

    Dim folderPath As String
    Dim password As String
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim file As String
    Dim subFolder As Object
    Dim fso As Object
    
    ' 弹窗选择目录
    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "请选择目录"
        .AllowMultiSelect = False
        If .Show <> -1 Then Exit Sub
        folderPath = .SelectedItems(1)
    End With
    
    Debug.Print "选择的目录: " & folderPath
    
    ' 弹窗输入密码
    password = InputBox("请输入保护密码:", "密码输入")
    
    Debug.Print "输入的密码: " & password
    
    ' 创建 FileSystemObject
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    ' 遍历目录中的Excel文件
    file = Dir(folderPath & "\*.xls*")
    Do While file <> ""
        Debug.Print "当前文件: " & file
        Set wb = Workbooks.Open(folderPath & "\" & file)
        For Each ws In wb.Worksheets
            ws.Protect Password:=password, DrawingObjects:=True, Contents:=True, Scenarios:=True
        Next ws
        wb.Close SaveChanges:=True
        file = Dir
    Loop
    
    ' 遍历子目录中的Excel文件
    Set subFolder = fso.GetFolder(folderPath)
    For Each subFolder In subFolder.SubFolders
        ProtectWorksheetsInSubFolder subFolder.Path, password
    Next subFolder
    
    MsgBox "操作完成!", vbInformation
End Sub

Sub ProtectWorksheetsInSubFolder(folderPath As String, password As String)
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim file As String
    
    ' 创建 FileSystemObject
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    ' 遍历子目录中的Excel文件
    file = Dir(folderPath & "\*.xls*")
    Do While file <> ""
        Debug.Print "当前子目录文件: " & file
        Set wb = Workbooks.Open(folderPath & "\" & file)
        For Each ws In wb.Worksheets
            ws.Protect Password:=password, DrawingObjects:=True, Contents:=True, Scenarios:=True
        Next ws
        wb.Close SaveChanges:=True
        file = Dir
    Loop
End Sub
posted @   Nlce2Cu  阅读(292)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示