为什么我的宏 运行 不会自动出现在 Word 中?
Why won't my macro run automatically in Word?
这是我第一次尝试 VBA 在 Word 中,尽管我在 Excel 中使用了很多。我想要做的是在打开我的 Word 模板文档后自动执行我的代码。这是我放在 Word 模板模块中的代码:
Private Sub AutoOpen()
Dim myValue
myValue = InputBox(prompt:="What is the client name", Title:="InputBox", Default:="Type your client name here")
stringReplaced = stringReplaced + "<Replace>"
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "<Replace>"
.Replacement.Text = myValue
.Wrap = wdFindContinue
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = False
.Execute Replace:=wdReplaceAll
End With
Next myStoryRange
End Sub
我正在使用 Word 2010。当我手动进入并单击 运行 时,我的代码 运行 就像我想要的那样。但是,当我关闭我的 Word 文档并重新打开时,什么也没有发生。我用谷歌搜索了这个问题,试图找到解决方案(并尝试了不同版本的 AutoOpen),但我不知道我做错了什么。关于为什么 AutoOpen 不自动执行的任何想法?
谢谢!
您应该将代码放在模板文档的标准模块中。接下来,将子名称从 AutoOpen()
更改为:
Sub AutoExec()
'..... your code here .....
End Sub
这是我第一次尝试 VBA 在 Word 中,尽管我在 Excel 中使用了很多。我想要做的是在打开我的 Word 模板文档后自动执行我的代码。这是我放在 Word 模板模块中的代码:
Private Sub AutoOpen()
Dim myValue
myValue = InputBox(prompt:="What is the client name", Title:="InputBox", Default:="Type your client name here")
stringReplaced = stringReplaced + "<Replace>"
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "<Replace>"
.Replacement.Text = myValue
.Wrap = wdFindContinue
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = False
.Execute Replace:=wdReplaceAll
End With
Next myStoryRange
End Sub
我正在使用 Word 2010。当我手动进入并单击 运行 时,我的代码 运行 就像我想要的那样。但是,当我关闭我的 Word 文档并重新打开时,什么也没有发生。我用谷歌搜索了这个问题,试图找到解决方案(并尝试了不同版本的 AutoOpen),但我不知道我做错了什么。关于为什么 AutoOpen 不自动执行的任何想法? 谢谢!
您应该将代码放在模板文档的标准模块中。接下来,将子名称从 AutoOpen()
更改为:
Sub AutoExec()
'..... your code here .....
End Sub