简体   繁体   English

Excel VBA:如何只允许宏进行单元格输入

[英]Excel VBA: How to only allow macro to make cell input

I'm currently working on a worksheet, which should use different userforms to perform tasks and calculations. 我目前正在处理一个工作表,该工作表应使用不同的用户窗体来执行任务和计算。 The userforms are called via buttons. 用户表单通过按钮调用。

So all the input by the user should be made via those userforms; 因此,用户的所有输入都应通过这些用户表单进行; the actual worksheet should contain only the results which should be read-only (for the user). 实际工作表应仅包含结果(对于用户而言)为只读。

Problems: 问题:

  1. Protecting the worksheet will also prevent the macro from making changes. 保护工作表也将阻止宏进行更改。
  2. The following code has the same issue as protecting the worksheet. 以下代码具有与保护工作表相同的问题。

     Private Sub Worksheet_Change(ByVal Target As Range) If Not IsEmpty(Target) Then Target.Clear MsgBox "SomeAlertMSG" End If End Sub 

Any suggestions how to accomplish this without using self-made boolean flags? 有什么建议如何在不使用自制布尔标志的情况下完成此操作?

Call another sub to write to the range for you and handle events like so: 调用另一个子程序为您写入范围并处理如下事件:

Sub WriteToCell(ByVal cell As Excel.Range, ByVal cellValue)
    Application.EnableEvents = False
        cell.Value = cellValue
    Application.EnableEvents = True
End Sub

Then in your userform when you want to write something to a range just write: 然后,在用户表单中,如果您想将内容写到某个范围内,只需编写:

WriteToCell Sheets("someSheet").Range("A1"), "I can stay here!"

What you are looking for here is the UserInterfaceOnly:=True flag for protecting sheets in VBA. 您在这里寻找的是UserInterfaceOnly:=True标志,用于保护VBA中的图纸。

Protect your sheet from VBA by the following line: 通过以下代码保护您的工作表免受VBA的侵害:

ActiveWorkbook.Sheets("YourSheet").Protect Password:="123", UserInterfaceOnly:=True

This will protect the sheet and prevent the user from editing it manually, however any macros can still change the sheet! 这将保护工作表并防止用户手动编辑它,但是任何宏仍然可以更改工作表! Obviously you can choose a different password, or have it as an input so it's not baked in/visible in your code. 显然,您可以选择一个不同的密码,或者将其作为输入,这样就不会在您的代码中显示该密码。

Documentation: https://msdn.microsoft.com/en-us/library/office/ff840611.aspx 文档: https : //msdn.microsoft.com/zh-cn/library/office/ff840611.aspx

UserInterfaceOnly - True to protect the user interface, but not macros. UserInterfaceOnly-为 True,以保护用户界面,但不保护宏。 If this argument is omitted, protection applies both to macros and to the user interface. 如果省略此参数,则保护既适用于宏,也适用于用户界面。

You can make your worksheet unprotected by using the below code in the code to be executed after clicking on macro. 通过单击宏后要执行的代码中的以下代码,可以使工作表不受保护。

Sheet1.Protect Password:="Secret"

After the code is executed then the sheet will get locked again. 执行代码后,工作表将再次被锁定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM