使用参数保护文件夹中的所有工作表

时间:2015-02-11 17:56:55

标签: excel vba excel-vba directory

我有以下代码,旨在使用某些参数保护桌面上特定文件夹中的每个工作表,例如允许对行进行排序,排序和过滤。

我的问题是代码根本没有运行。我从这个网站和Excel提示中收集了一些代码,以便根据我想要完成的内容进行自定义。

Sub ProtectAllSheets()
    Dim sh As Worksheet
    Dim myPassword As String
    Dim wBk As Workbook
    Dim sFileSpec As String
    Dim sPathSpec As String
    Dim sFoundFile As String
    myPassword = "random"
    sPathSpec = "C:\Users\Name\Desktop\Folder"
    sFileSpec = "*.xlsx"
    sFoundFile = Dir(sPathSpec & sFileSpec)
    Do While sFoundFile = ""
        Set wBk = Workbooks.Open(sPathSpec & sFoundFile)
        With wBk
            For Each sh In wBk.Worksheets
                sh.Protect Password:=myPassword, AllowInsertingRows:=True, AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True
            Next sh
            Application.DisplayAlerts = False
            wBk.SaveAs Filename:=.FullName
            Application.DisplayAlerts = True
        End With
        Set wBk = Nothing
        Workbooks(sFoundFile).Close 
        sFoundFile = Dir
    Loop
End Sub

阻止此代码运行我做错了什么?

1 个答案:

答案 0 :(得分:0)

看起来你正在从某个地方复制代码。你遇到的一些问题:

  1. 使用sPathSpec时,最后需要\
  2. 确保桌面上的文件夹确实存在,如果不同,则更改代码
  3. 尽可能使用环境变量Environ("USERPROFILE")为您提供运行此宏的用户的配置文件路径
  4. 您的Do-Loop错了!您应该停止直到找不到文件而不是循环时找不到任何内容
  5. 您应确保在更改文件之前成功打开文件
  6. 使用With wBk ...
  7. 的原因

    我更改了一些行以提高性能,并更改了Debug行以列出保存的所有文件。

    所以你应该试试这个:

    Sub ProtectAllSheets()
        Const myPassword = "random"
        Dim sh As Worksheet
        Dim wBk As Workbook
        Dim sFileSpec As String
        Dim sPathSpec As String
        Dim sFoundFile As String
    
        sPathSpec = Environ("USERPROFILE") & "\Desktop\Folder\"
        sFileSpec = "*.xlsx"
        sFoundFile = Dir(sPathSpec & sFileSpec)
        Application.DisplayAlerts = False
        Do Until sFoundFile = ""
            Set wBk = Workbooks.Open(sPathSpec & sFoundFile)
            If Not wBk Is Nothing Then
                With wBk
                    For Each sh In .Worksheets
                        sh.Protect Password:=myPassword, AllowInsertingRows:=True, AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True
                    Next sh
                    .Save
                    Debug.Print "Saved: " & .FullName
                    .Close
                End With
                Set wBk = Nothing
            End If
            sFoundFile = Dir
        Loop
        Application.DisplayAlerts = True
    End Sub