2013-05-02 70 views
0

我有以下VBA代碼以書籤格式在代碼位置插入日期。它每次打開文件時都插入日期而不刪除舊的Boookmark文本,所以我在代碼的頂部添加了刪除文本,但現在它刪除了格式,並且它插入了文本是否有保留格式的方法?Word(2010)更新日​​期並使用宏保持格式化

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 
+0

代碼的頂部代碼會刪除書籤,因此您無法在下面運行「With ...」部分。我錯過了什麼,或者你錯過了一部分代碼? – 2013-05-02 12:44:24

+0

KazJaw,代碼按原樣運行。書籤保持不變,Withs的輸出工作,並按照每個書籤所定義的位置代碼格式輸出日期。以上是我在文檔中的完整代碼。 – RebelCom 2013-05-03 09:24:10

回答

0

當你說'格式'你是指日期格式,或粗體/斜體等?

在任何情況下,您的代碼不會爲我運行;當您刪除範圍時,書籤會隨之一起移除。對我來說,以下運行,正確格式每個I運行時間日期:

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 

您可以繼續它的書籤的休息或扔在整個事件中的循環。