vba 在word文档中插入日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3448985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
insert date in a word document
提问by Marc
I'm working on a Word document which has a table on each page. Each table contains several occurrences of the word "Datum". By double-clicking this word "Datum", this word should be replaced with the system date. And this date should be "frozen", i.e. it mustn't adapt itself when opening the document on a different day.
我正在处理一个 Word 文档,每个页面上都有一个表格。每个表都包含多次出现的单词“Datum”。通过双击“Datum”这个词,这个词应该被系统日期替换。并且这个日期应该被“冻结”,即在不同的日期打开文档时它不能自行调整。
Is there anyone who can help me out with the code for this?
有没有人可以帮我解决这个问题的代码?
回答by Dirk Vollmar
You can do that using a macro button field:
您可以使用宏按钮字段执行此操作:
- Press Ctrl + F9 to create a new field
Enter the following text within the curly braces:
MACROBUTTON InsertDateTime Datum
The result will look as follows:
{ MACROBUTTON InsertDateTime Datum }
Press Alt + F9 to toggle field code display
- 按 Ctrl + F9 创建一个新字段
在花括号内输入以下文本:
MACROBUTTON InsertDateTime Datum
结果如下:
{ MACROBUTTON InsertDateTime Datum }
按 Alt + F9 切换域代码显示
This will show Words built-in Insert Datedialog. If you don't want to display the dialog you can replace InsertDateTime
with the name of a custom VBA macro, e.g. MyModule.MyInsertDate
. This macro would replace the field with the current date:
这将显示 Words 内置的插入日期对话框。如果您不想显示对话框,您可以替换InsertDateTime
为自定义 VBA 宏的名称,例如MyModule.MyInsertDate
. 此宏将用当前日期替换该字段:
Public Sub Test()
Selection.Text = Now
End Sub
回答by Ifusaso
Try making each Datum a Field{MacroButton datumToDate Datum} that calls a Word VBA:
尝试使每个 Datum 成为调用 Word VBA的Field{MacroButton datumToDate Datum}:
Sub datumToDate()
Selection.InsertDateTime Format(Now(), "yyyy-mm-dd")
End Sub
Obviously feel free to edit yyyy-mm-dd to any valid time format. This should use Selection Object's InsertDateTimeto replace the 'current selection', here your field labeled Datum. It only replaces the current Datum because it goes off of where you were when you began the Sub.
显然可以随意将 yyyy-mm-dd 编辑为任何有效的时间格式。这应该使用选择对象的 InsertDateTime来替换“当前选择”,这里您的字段标记为 Datum。它只会替换当前的 Datum,因为它与您开始 Sub 时所处的位置不同。
To activate MacroButton Fields, you will have to double click unless you run
要激活宏按钮字段,除非您运行,否则您必须双击
Sub AutoOpen()
Options.ButtonFieldClicks = 1
End Sub
in the ThisDocument location. I advise against this because it's easy for someone to accidentally click a Datum in an old table and reset the date to Now and I'm not positive that the Selection Method will work if you don't double click the Field (although it should).
在 ThisDocument 位置。我建议不要这样做,因为有人很容易不小心单击旧表中的基准并将日期重置为“现在”,如果您不双击该字段,我不确定选择方法是否会起作用(尽管它应该) .