【问题标题】:Force people to enable Word macros强制人们启用 Word 宏
【发布时间】:2021-05-09 18:09:45
【问题描述】:

我想确保打开我的 Word 文档的每个人都启用宏。我想到了一个带有以下文本的文档:“请启用宏以查看此文档”,如果确实启用了宏,我想用原始内容修改文件以使其看起来正常。

有没有我可以在 VBA 中做到这一点?

提前致谢,
罗宾

【问题讨论】:

  • 您希望代码确保用户运行此代码?
  • 听起来好像您正在尝试创建恶意软件。
  • 试图强迫用户启用宏,充其量是非常不负责任的。任何这样做的文档都应该非常正确地被视为恶意软件。我强烈建议您寻找其他解决方案。

标签: vba ms-word


【解决方案1】:

首先,您必须知道,这不能用于实验过的 VBA 用户...

  1. 当然,您的文档必须是 .docm 类型(启用宏的文档);

  2. 请复制ThisDocument代码模块中的下一个代码:

Option Explicit

Const bookMrk As String = "BlockBMrk"


Private Sub Document_Close()
    If ThisDocument.Bookmarks.Exists(bookMrk) = True Then
        With ThisDocument
            .ActiveWindow.View.Type = wdPrintPreview
            If ThisDocument.ProtectionType = -1 Then .Protect wdAllowOnlyFormFields, , "testPass", , True
            .Save
        End With
    Else
        If ThisDocument.ProtectionType = 2 Then ThisDocument.Unprotect "testPass"
        With Selection
            .HomeKey Unit:=wdStory
            .TypeText Text:="Please re-open this file with ""Enable Macros"" selected." & vbCrLf & _
                            "Otherwise, you cannot see its content..." & vbCrLf & vbCrLf & _
                            " To be able to enable macros go File -> Options -> Trust Center -> " & _
                            "Trust Center Settings... -> Macro Settings and check 'Disable all macros with notification' and press OK."
            
            .InsertBreak Type:=wdPageBreak
            .HomeKey Unit:=wdStory, Extend:=wdExtend
            ThisDocument.Bookmarks.Add Name:=bookMrk, _
            Range:=Selection.Range
        End With
        With ThisDocument
            .ActiveWindow.View.Type = wdPrintPreview
            .Protect wdAllowOnlyFormFields, Password:="testPass"
            .Save
        End With
    End If
End Sub

Private Sub Document_Open()
    MacrosEnabled
End Sub

Sub MacrosEnabled()
    ThisDocument.Unprotect Password:="testPass"
    ThisDocument.Bookmarks(bookMrk).Select
    Selection.Delete
End Sub

2 之二。保护(以某种方式)不被看到的 VBA 代码:

   a. Right click on the document Project (being in VBE);
   b. Choose 'Protection' tab;
   c. Check 'Lock project for viewing';
   d. Set a password (keep it in your mind, if need to modify something...);
   e. Confirm the password and press 'OK'

但是你要知道破解这个密码并不是很复杂(对于有经验的人来说)。

  1. 在文档中写一些东西(随便你),保存文档并关闭它。

  2. 在启用或不启用宏的情况下打开它,看看发生了什么...

请测试上述解决方案并发送一些反馈。

【讨论】:

  • 添加保护只会阻止用户编辑文档,而不是查看它。
  • 嗨!感谢您及时的回复。它工作得很好,但我有几个问题:启用宏时我在哪里放置自己的代码,禁用宏时的消息现在未保存,我可以使用 VBA 自动保存它吗?现在,禁用宏时的消息是标题,如何更改样式以使其成为正常的 12px 黑色文本?
  • @Timothy Rylatt 请尝试解决方案并在此之后发表评论......
  • @Robin:这取决于“我自己的代码”的含义......通常,您应该插入一个标准模块并将其放置在那里。如果它应该是一个事件,也将它放在ThisDocument模块中。
  • 我的评论仍然有效。 OP 想要隐藏文档的全部内容。您提出的解决方案没有实现这一点。有一种方法可以实现它,但我绝对不会在公共论坛上分享它。整个问题本质上是“我如何创建基于 VBA 的恶意软件?”
猜你喜欢
  • 1970-01-01
  • 2018-08-30
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多