vba VBA代码仅锁定Excel中用户选择(突出显示)的单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17652421/
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-11 22:13:38  来源:igfitidea点击:

VBA code to lock only user selected (Highlighted) cells in excel

excelvba

提问by chris

I was wondering how can i one use VBA/macros to lock certain excel cells that are selected/highlighted by the user.

我想知道如何使用 VBA/宏来锁定用户选择/突出显示的某些 excel 单元格。

The code im using right now is locking the entire sheet.

我现在使用的代码是锁定整个工作表。

Sub Macro4()
'
' Macro4 Macro
'

'
  Worksheets("Sheet1").Activate
  ActiveSheet.Unprotect
Cells.Select
Selection.Locked = True
ActiveSheet.Protect
End Sub

Any ideas on what im doing wrong?

关于我做错了什么的任何想法?

Thank you for your time.

感谢您的时间。

回答by varocarbas

If you want to perform any actions on the selected cell(s) every time a new selection occurs, you should rely on the code being triggered when this happens:

如果您想在每次发生新选择时对所选单元格执行任何操作,您应该依赖发生这种情况时触发的代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

  Selection.Locked = True

End Sub

This inside the file with the code for the given sheet; that is, if you want to consider Sheet1, the file where you have to write this code is: Microsoft Excel Objects/Sheet1 (Sheet1).

这在包含给定工作表代码的文件中;也就是说,如果您要考虑Sheet1,您必须编写此代码的文件是:Microsoft Excel Objects/Sheet1 (Sheet1).

UPDATE AFTER YOUR COMMENT

在您发表评论后更新

Sub Button1_Click()
      Selection.Locked = True
End Sub

This code locks all the cells selected when the Button1is clicked.

此代码会在Button1单击时锁定所有选定的单元格。