Excel VBA: 如何只允许宏进行单元格输入
Excel VBA: How to only allow macro to make cell input
我目前正在处理一个工作表,它应该使用不同的用户表单来执行任务和计算。用户表单通过按钮调用。
所以用户的所有输入都应该通过这些用户表单进行;实际的工作表应该只包含应该只读的结果(对于用户)。
问题:
- 保护工作表还将防止宏进行更改。
以下代码与保护工作表有同样的问题。
Private Sub Worksheet_Change(ByVal Target As Range)
If Not IsEmpty(Target) Then
Target.Clear
MsgBox "SomeAlertMSG"
End If
End Sub
关于如何在不使用自制布尔标志的情况下完成此操作的任何建议?
调用另一个 sub 为您写入范围并像这样处理事件:
Sub WriteToCell(ByVal cell As Excel.Range, ByVal cellValue)
Application.EnableEvents = False
cell.Value = cellValue
Application.EnableEvents = True
End Sub
然后在你的用户表单中,当你想写一些东西到一个范围时,只需写:
WriteToCell Sheets("someSheet").Range("A1"), "I can stay here!"
您可以在点击宏后执行的代码中使用以下代码使您的作品sheet不受保护。
Sheet1.Protect Password:="Secret"
代码执行后 sheet 将再次被锁定。
您在这里寻找的是 UserInterfaceOnly:=True
标志,用于保护 VBA 中的 sheet。
通过以下行保护您的 sheet 免受 VBA 侵害:
ActiveWorkbook.Sheets("YourSheet").Protect Password:="123", UserInterfaceOnly:=True
这将保护 sheet 并防止用户手动编辑它,但是任何宏仍然可以更改 sheet!显然,您可以选择不同的密码,或者将其作为输入,这样它就不会在您的代码中烘焙 in/visible。
文档:https://msdn.microsoft.com/en-us/library/office/ff840611.aspx
UserInterfaceOnly - True to protect the user interface, but not macros. If this argument is omitted, protection applies both to macros and to the user interface.
我目前正在处理一个工作表,它应该使用不同的用户表单来执行任务和计算。用户表单通过按钮调用。
所以用户的所有输入都应该通过这些用户表单进行;实际的工作表应该只包含应该只读的结果(对于用户)。
问题:
- 保护工作表还将防止宏进行更改。
以下代码与保护工作表有同样的问题。
Private Sub Worksheet_Change(ByVal Target As Range) If Not IsEmpty(Target) Then Target.Clear MsgBox "SomeAlertMSG" End If End Sub
关于如何在不使用自制布尔标志的情况下完成此操作的任何建议?
调用另一个 sub 为您写入范围并像这样处理事件:
Sub WriteToCell(ByVal cell As Excel.Range, ByVal cellValue)
Application.EnableEvents = False
cell.Value = cellValue
Application.EnableEvents = True
End Sub
然后在你的用户表单中,当你想写一些东西到一个范围时,只需写:
WriteToCell Sheets("someSheet").Range("A1"), "I can stay here!"
您可以在点击宏后执行的代码中使用以下代码使您的作品sheet不受保护。
Sheet1.Protect Password:="Secret"
代码执行后 sheet 将再次被锁定。
您在这里寻找的是 UserInterfaceOnly:=True
标志,用于保护 VBA 中的 sheet。
通过以下行保护您的 sheet 免受 VBA 侵害:
ActiveWorkbook.Sheets("YourSheet").Protect Password:="123", UserInterfaceOnly:=True
这将保护 sheet 并防止用户手动编辑它,但是任何宏仍然可以更改 sheet!显然,您可以选择不同的密码,或者将其作为输入,这样它就不会在您的代码中烘焙 in/visible。
文档:https://msdn.microsoft.com/en-us/library/office/ff840611.aspx
UserInterfaceOnly - True to protect the user interface, but not macros. If this argument is omitted, protection applies both to macros and to the user interface.