0

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

    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
4

1 回答 1

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

您可以在其余的书签中继续它,或者将整个内容放在一个循环中。

于 2013-05-07T20:16:20.220 回答