excel - 仅对公式单元格执行操作时出错

标签 excel vba for-loop

我试图循环遍历文件夹中每个工作簿中的每个工作表,并确保仅锁定包含公式的单元格。我已经成功使用代码锁定每个工作表中的所有单元格,并使用代码锁定工作表中的每个公式,成功了几个月,所以我基本上将这两段代码混在一起得到这个:

Sub LockAllFormulas()

Dim myOldPassword As String
Dim myNewPassword As String
Dim ws As Worksheet
Dim FileName As String
Dim rng As Range

myOldPassword = InputBox(Prompt:="Please enter the previously used password.", Title:="Old password input")
myNewPassword = InputBox(Prompt:="Please enter the new password, if any.", Title:="New password input")

FileName = Dir(CurDir() & "\" & "*.xls")
Do While FileName <> ""
Application.DisplayAlerts = False
If FileName <> "ProtectionMacro.xlsm" Then
    MsgBox FileName
    Workbooks.Open (CurDir & "\" & FileName)
    For Each ws In ActiveWorkbook.Worksheets
        If Not Cells.SpecialCells(xlCellTypeFormulas) Is Nothing Then
            ActiveWorkbook.ActiveSheet.Unprotect Password:=myOldPassword
            ActiveWorkbook.ActiveSheet.Cells.Locked = False
            For Each rng In ws.Cells.SpecialCells(xlCellTypeFormulas)
                rng.Locked = True
            Next rng
            ActiveWorkbook.ActiveSheet.Protect Password:=myPassword
        End If
    Next ws
    ActiveWorkbook.Save
    ActiveWorkbook.Close
End If
FileName = Dir()
Loop
Application.DisplayAlerts = True


End Sub

每次运行它都会显示 400 错误。该错误与每当代码运行到其中没有任何代码的工作表时遇到的错误相匹配,但我认为在添加时我解决了该问题:

If Not Cells.SpecialCells(xlCellTypeFormulas) Is Nothing Then

你知道还有什么可能出问题吗?

最佳答案

使用SpecialCells时,您必须非常小心。我所做的是将它们存储在 OERN 之间的范围内,然后检查它们是否是什么。这是一个例子

Dim rng  As Range

On Error Resume Next
Set rng = ws.Cells.SpecialCells(xlCellTypeFormulas)
On Error GoTo 0

If Not rng Is Nothing Then
    '
    '~~> Rest of the code
    '
End If

将其应用到您的代码中将如下所示(未经测试)

Dim LockedRange As Range

For Each ws In ActiveWorkbook.Worksheets
    With ws
        On Error Resume Next
        Set LockedRange = .Cells.SpecialCells(xlCellTypeFormulas)
        On Error GoTo 0

        If Not LockedRange Is Nothing Then
            .Unprotect Password:=myOldPassword

            .Cells.Locked = False
            LockedRange.Locked = True

            .Protect Password:=myPassword
        End If

        Set LockedRange = Nothing
    End With
Next ws

关于excel - 仅对公式单元格执行操作时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25165819/

相关文章:

excel - 从 Powershell 调用具有不同参数计数的 VBA 函数

excel - 检查是否选择了多个单元格

Python 排序数据 for 循环和 if 语句

vba - 通过匹配Header传输数据

基于 C++ 范围的 for 循环给出 SIGABRT,而普通循环工作正常

c++ - C++中的数组乘法

excel - 如何仅使用函数/方程对表进行排序

sql-server - Excel VBA 和 ADODB : retrieve auto identity of row inserted into SQL Server from VBA

excel - 如何让 excel 在执行宏时显示等待消息?

vba - 如何通过Selenium和VBA根据html从第2行第2列中提取文本8