我有以下代码,旨在使用某些参数保护桌面上特定文件夹中的每个工作表,例如允许对行进行排序,排序和过滤。
我的问题是代码根本没有运行。我从这个网站和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
阻止此代码运行我做错了什么?
答案 0 :(得分:0)
看起来你正在从某个地方复制代码。你遇到的一些问题:
sPathSpec
时,最后需要\
Environ("USERPROFILE")
为您提供运行此宏的用户的配置文件路径Do-Loop
错了!您应该停止直到找不到文件而不是循环时找不到任何内容 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