Excel VBA循环浏览工作簿中的所有工作表
我曾尝试过以下VBA代码,我想为活动工作簿中的所有可用工作表运行此代码,我认为我犯了一个小错误,由于我是初学者,我无法找到它,请帮助修复它Excel VBA循环浏览工作簿中的所有工作表,excel,vba,Excel,Vba,我曾尝试过以下VBA代码,我想为活动工作簿中的所有可用工作表运行此代码,我认为我犯了一个小错误,由于我是初学者,我无法找到它,请帮助修复它 Sub ProtectFormulas() Dim strPassword As String Dim ws As Worksheet For Each ws In Sheets ws.Activate .Unprotect .Cells.Locked = False .Cells.SpecialCells(xlCellTyp
Sub ProtectFormulas()
Dim strPassword As String
Dim ws As Worksheet
For Each ws In Sheets
ws.Activate
.Unprotect
.Cells.Locked = False
.Cells.SpecialCells(xlCellTypeFormulas).Locked = True
.Cells.SpecialCells(xlCellTypeFormulas).FormulaHidden = True
.Protect AllowDeletingRows:=True
strPassword = 123456
ActiveSheet.Protect Password:=strPassword
Next ws
End With
End Sub
任何帮助都会以感谢的方式表示。您的代码有3个问题:
.Cells.SpecialCells(xlCellTypeFormulas).Locked = True
.Cells.SpecialCells(xlCellTypeFormulas).FormulaHidden = True
因为如果没有公式,那么.Cells.SpecialCells(xlCellTypeFormulas)
是无
的,因此没有.Locked
和.FormulaHidden
方法
工作表
和工作表
进行混合。请注意,这些是不一样的
是所有类型工作表(工作表、图表表等)的集合工作表
是工作表类型的集合工作表
Dim ws声明为工作表
,并且文件中有一个图表表,那么对于工作表中的每个ws
将出错,因为您试图将图表表推入定义为工作表
且不能包含图表表的变量ws
。尽可能具体,尽可能使用工作表
,以支持工作表
Option Explicit
'if this is not variable make it a constant and global so you can use it in any procedure
Const strPassword As String = "123456"
Sub ProtectFormulas()
'Dim strPassword As String
'strPassword = "123456" 'remove this here if you made it global
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
With ws
.Activate 'I think this is not needed
.Unprotect Password:=strPassword 'unprotect probably needs your password too or this will not work once the worksheet was protected.
.Cells.Locked = False
Dim FormulaCells As Range
Set FormulaCells = Nothing 'initialize (because we are in a loop!)
On Error Resume Next 'hide error messages (next line throws an error if no forumla is on the worksheet
Set FormulaCells = .Cells.SpecialCells(xlCellTypeFormulas)
On Error Goto 0 ' re-enable error reporting! Otherwise you won't see errors if they occur!
If Not FormulaCells Is Nothing Then 'check if there were formulas to prevent errors if not
FormulaCells.Locked = True
FormulaCells.FormulaHidden = True
End If
.Protect AllowDeletingRows:=True, Password:=strPassword
End With
Next ws
End Sub
运行时是否有任何错误是的,它在
上给出了错误。取消保护
即无效或不合格的引用,每行代码中都缺少ws。好的,明白了,谢谢你的语气,感谢你付出努力并抽出时间