Word(2010)更新日​​期并使用宏保持格式

时间:2013-05-02 12:13:54

标签: vba ms-word word-vba

我有以下VBA代码,以书签位置的代码格式插入日期。它是在每次打开文件时插入日期而不删除旧的Boookmark文本所以我在代码顶部添加了删除文本但是现在它删除了格式并且插入文本是否有办法保持格式化?

    Sub AutoOpen()
'
' AutoOpen Macro
'
'
 ActiveDocument.Bookmarks("MyDate").Range.Delete
 ActiveDocument.Bookmarks("MyDate1").Range.Delete
 ActiveDocument.Bookmarks("MyDate2").Range.Delete
 ActiveDocument.Bookmarks("MyDate3").Range.Delete
 ActiveDocument.Bookmarks("MyDate4").Range.Delete
 ActiveDocument.Bookmarks("MyDate5").Range.Delete
 ActiveDocument.Bookmarks("MyDate6").Range.Delete

      With ActiveDocument.Bookmarks("MyDate").Range
         .InsertBefore Format(Date + 1, "dddd dd mmmm yyyy")
      End With

    With ActiveDocument.Bookmarks("MyDate1").Range
        .InsertBefore Format(Date + 2, "dddd dd mmmm yyyy")
    End With

    With ActiveDocument.Bookmarks("MyDate2").Range
        .InsertBefore Format(Date + 3, "dddd dd mmmm yyyy")
    End With

    With ActiveDocument.Bookmarks("MyDate3").Range
        .InsertBefore Format(Date + 4, "dddd dd mmmm yyyy")
    End With

    With ActiveDocument.Bookmarks("MyDate4").Range
       .InsertBefore Format(Date + 5, "dddd dd mmmm yyyy")
     End With

    With ActiveDocument.Bookmarks("MyDate5").Range
       .InsertBefore Format(Date + 6, "dddd dd mmmm yyyy")
    End With

    With ActiveDocument.Bookmarks("MyDate6").Range
        .InsertBefore Format(Date + 7, "dddd dd mmmm yyyy")
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

当您说'格式化'时,您的意思是日期格式,还是粗体/斜体等?

在任何情况下,您的代码都不适合我;当您删除书签随附的范围时。以下为我运行,并在每次运行时正确格式化日期:

Dim tempRng As Range

Set tempRng = ActiveDocument.Bookmarks("MyDate").Range
tempRng.Text = Format(Date + 1, "dddd dd mmmm yyyy")
ActiveDocument.Bookmarks.Add "MyDate", tempRng

Set tempRng = ActiveDocument.Bookmarks("MyDate1").Range
tempRng.Text = Format(Date + 2, "dddd dd mmmm yyyy")
ActiveDocument.Bookmarks.Add "MyDate1", tempRng

Set tempRng = ActiveDocument.Bookmarks("MyDate2").Range
tempRng.Text = Format(Date + 3, "dddd dd mmmm yyyy")
ActiveDocument.Bookmarks.Add "MyDate2", tempRng

您可以将其继续用于其余的书签,或将整个内容循环播放。