VBA 宏以跳过已经 运行 的宏

VBA Macro to skip a macro that has already run

我在 mac 文档的受保护字 2011 中有一个文本表单字段,它在退出时触发 macro 到 运行。 macro 使用各种信息填充表单,但不依赖于输入到该特定表单字段中的测试。我有两个想法来解决这个问题。如果可以的话,第一个选项是最好的,否则第二个选项将是一个合理的解决方法。有人可以帮忙找到一个执行以下操作之一的 macro 吗?

一个。如果再次输入并编辑表单字段,是否会阻止 macro 运行ning 第二次?

b。在输入表单域时检查是否已经有文本,如果有,则阻止编辑并移至下一个表单域,而无需 运行 在退出时再次 macro ?

我是 VBA 的新手,但我认为我掌握了基础知识。这是我为 b 想出的。解决方案,但它不起作用。

A macro 检查表单字段名称中是否有文本 "text9",如果有,则取消保护,转到书签 "text10" 并保护表单。否则,允许用户在退出时填写表单字段和 运行 macro。

Sub TestSkipField()
'
' TestSkipField Macro
'
'
With GetCurrentFF
If Len(.Result) = Null Then
End If
Else
            If ActiveDocument.ProtectionType <> wdNoProtection Then
            ActiveDocument.UnProtect
            End If
            Selection.GoTo What:=wdGoToBookmark, Name:="Text10"
                With ActiveDocument.Bookmarks
                .DefaultSorting = wdSortByName
                .ShowHidden = False
            End With
        ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True
End If
End With
End Sub

我认为解决您的问题的最简单方法是使用一个全局变量来回答问题 "has the macro already run?"。

假设您有如下宏:

Sub myMacro()
    'your stuff here
End Sub

您不希望此宏 运行 两次。然后,您可以在模块顶部定义一个全局变量:

Dim hasRun As Boolean 'this will be False by default
Sub myMacro()
    'your stuff here
End Sub
Sub myOtherMacro()
    'some other stuff here
End Sub
'etc.

然后将支票嵌入到您的宏中:

Sub myMacro()
    If hasRun = False Then 'if hasRun is still False, it means we never ran this code yet
        'do your stuff here
        hasRun = True 'set hasRun = True, so from now we know that this code has already been executed once
    End If
End Sub

这应该允许您不更改代码结构或对数据执行检查,但同时只执行一次宏。你可以按照这个方向来详细说明执行条件:只执行两次,只有在发生某些事情时等。

请注意: 您最好在宏代码的最后设置 hasRun = True,以确保值 hasRun 不会如果执行直到所需代码结束才到达,则为 True。