使用 VBA 在 Excel 中锁定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24451626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:36:49  来源:igfitidea点击:

Lock rows in Excel using VBA

excelvbaexcel-vba

提问by user969113

I have an Excel sheet with columns A to F to be filled out by different users. Once one row is completed another user (control user) enteres "done" in column G. As soon as the user entered "done" in coulmn G, I want a VBA script to lock the entire row (column A to G) so that no one can change any of that row entries any longer. Is that possible using VBA scripting?

我有一个 Excel 工作表,其中 A 到 F 列由不同的用户填写。一旦一行完成,另一个用户(控制用户)在 G 列中输入“完成”。一旦用户在 G 列中输入“完成”,我想要一个 VBA 脚本来锁定整行(A 列到 G 列),以便没有人可以再更改任何该行条目。可以使用 VBA 脚本吗?

回答by Gary's Student

We must start with all cells un-protectedand the sheet Locked

我们必须从所有未受保护的单元格和已锁定的工作表开始

Enter the following Event macroin the worksheet code area:

在工作表代码区域中输入以下事件宏

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim N As Long
    N = Target.Row
    If Intersect(Target, Range("G:G")) Is Nothing Then Exit Sub
    If Target.Text <> "Done" Then Exit Sub
    ActiveSheet.Unprotect
      Range("A" & N & ":G" & N).Locked = True
    ActiveSheet.Protect
End Sub

Because it is worksheet code, it is very easy to install and automatic to use:

因为是工作表代码,所以很容易安装,自动使用:

  1. right-click the tab name near the bottom of the Excel window
  2. select View Code - this brings up a VBE window
  3. paste the stuff in and close the VBE window
  1. 右键单击 Excel 窗口底部附近的选项卡名称
  2. 选择查看代码 - 这会打开一个 VBE 窗口
  3. 粘贴内容并关闭 VBE 窗口

If you have any concerns, first try it on a trial worksheet.

如果您有任何疑虑,请先在试用工作表上尝试。

If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

如果您保存工作簿,宏将与它一起保存。如果您使用的是 2003 年以后的 Excel 版本,则必须将文件另存为 .xlsm 而不是 .xlsx

To remove the macro:

要删除宏:

  1. bring up the VBE windows as above
  2. clear the code out
  3. close the VBE window
  1. 调出如上的 VBE 窗口
  2. 清除代码
  3. 关闭 VBE 窗口

To learn more about macros in general, see:

要了解有关一般宏的更多信息,请参阅:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (worksheet code), see:

要了解有关事件宏(工作表代码)的更多信息,请参阅:

http://www.mvps.org/dmcritchie/excel/event.htm

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!

必须启用宏才能使其工作!