首页 > 解决方案 > 每小时或 30 分钟锁定使用过的单元格

问题描述

我有很多人使用的文件。他们不时输入数据。我已经锁定和解锁了单元格,因此人们可以输入数据,但不要弄乱生成的数据(如时间)。我有一个代码会在每次输入后锁定单元格,但是如果有人输入了错误的数据,如果我不在,就无法撤消。

所以我决定创建 VBA 代码来每 X 分钟锁定一次所有使用过的单元格(所以如果有人犯了错误来修复它)但不知道如何做分钟部分。

我发现了这个很好的代码来锁定使用过的单元格:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
On Error Resume Next
'Resume to next line if any error occurs
 Dim Cell As Range
 With ActiveSheet
 'first of all unprotect the entire
 'sheet and unlock all cells
 .Unprotect Password:=""
 .Cells.Locked = False
 'Now search for non blank cells
 'and lock them and unlock blank cells
 For Each Cell In ActiveSheet.UsedRange
 If Cell.Value = "" Then
 Cell.Locked = False
 Else
 Cell.Locked = True
 End If
 Next Cell
 .Protect Password:=""
 'Protect with blank password, you can change it
 End With
Exit Sub
End Sub

我唯一需要的是添加一个代码以每 30 分钟或 1 小时执行一次上述操作。不知道 Sub 应该是这个Sub Workbook_BeforeSave还是AfterSave这个,因为在每个条目之后,文件会自动保存自己,或者应该像模块一样。

先感谢您。

标签: excel

解决方案


谢谢里卡多。

我设法创建了这个:

Private Sub save_cells()
On Error Resume Next
'Resume to next line if any error occurs
 Dim Cell As Range
 With ActiveSheet
 'first of all unprotect the entire
 'sheet and unlock all cells
 .Unprotect Password:="0"
 .Cells.Locked = False
 'Now search for non blank cells
 'and lock them and unlock blank cells
 For Each Cell In ActiveSheet.UsedRange
 If Cell.Value = "" Then
 Cell.Locked = False
 Else
 Cell.Locked = True
 End If
 If Cell.HasFormula Then
Cell.Locked = True
Cell.FormulaHidden = True
End If
 Next Cell
 .Protect Password:="0"
 'Protect with blank password, you can change it
 End With
 Application.SendKeys "{RIGHT}{LEFT}"
 Call savetimer
Exit Sub
End Sub

 Sub savetimer()
    Application.OnTime TimeValue("23:15:30"), "save_cells"
End Sub

我现在唯一的问题是,当我每 15 分钟左右将其锁定时,代码正在扫描所有行并让我的文件变慢。出于这个原因,我决定每天锁一次牢房。

如果有人知道如何修改代码以仅扫描 A3:O600 那就太好了。


推荐阅读