2015-02-11 56 views
0

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

我的问题是代码根本不运行。我从这个网站收集了一些代码和Exceltips,以便为我想完成的任务进行定制。

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 

我在做什么错误,以防止此代码运行?

+0

是不是在所有运行或正在运行,并且引发错误?我的第一印象是'Workbooks.Open(sPathSpec&sFoundFile)'应该是'Workbooks.Open(sPathSpec&“\”&sFoundFile)' – 2015-02-11 18:04:25

+0

是的,或者只是'sPathSpec =“C:\ Users \ Name \ Desktop \ “ – Jeanno 2015-02-11 19:08:59

+0

当我尝试这种方法时,它给了我错误1004”我们找不到C:\ Users \ Name \ Desktop \ Folder \“。 – 2015-02-11 20:34:43

回答

0

看起来像是从某处复制代码。有几个问题,你有:

  1. 与您使用的sPathSpec,你需要有\
  2. 确保在桌面上的文件夹不存在,如果不同的变化的代码
  3. 使用环境变量时可能Environ("USERPROFILE")为您提供运行此宏的用户的配置文件路径
  4. 您的Do-Loop错了!你应该停止,直到没有文件发现代替循环时,没有发现
  5. 您应该确保该文件正在改变它
  6. 使用With wBk的原因之前成功打开...

我已经改变了一些行以提高性能,并且使用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