开发者

insert date in a word document

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开发者_Go百科", 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.

Is there anyone who can help me out with the code for this?


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

This will show Word's built-in Insert Date dialog. 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:

Public Sub InsertCurrentDate()
    Selection.Text = Now
End Sub


Try making each Datum a Field {MacroButton datumToDate Datum} that calls a Word VBA:

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 InsertDateTime to 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.

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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜