如何使用VBA替换Word文档中已调整完成的时间戳
解决方法
你只需在注释'--> need to replace existing timestamp here.的位置添加2行代码即可完成替换:
- 第一行直接对当前匹配到的Range对象
c的Text属性赋值,把调整后的新时间戳覆盖旧时间戳 - 第二行将Range折叠到匹配内容的末尾,避免后续查找重复匹配到刚替换的内容,防止死循环
修改后完整代码
Sub FindAndReplace() ' ' vba string functions ' Dim c As Range Dim StartWord As String, EndWord As String Debug.Print Debug.Print "start of FindAndReplace() at " & Time() & " on " & Date Debug.Print "ActiveWindow.Parent (word document name) is " & ActiveWindow.Parent Debug.Print Set c = ActiveDocument.Content c.Find.ClearFormatting c.Find.Replacement.ClearFormatting With c.Find .Text = "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" ' Time stamp format .Replacement.Text = "" .Forward = True .Wrap = wdFindStop .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = True .MatchSoundsLike = False .MatchAllWordForms = False End With Dim FirstDate As Date ' Declare variables. Dim IntervalType As String Dim Number As Integer Dim message As String ' 如需动态输入偏移秒数,取消下一行注释,注释掉Number=45的行即可 'Number = InputBox("Enter number of seconds") Number = 45 Debug.Print "Number is " & Number Debug.Print IntervalType = "s" ' interval in seconds c.Find.Execute While c.Find.Found Debug.Print "c.Text is " & c.Text message = DateAdd(IntervalType, Number, c.Text) Debug.Print "adjusted time stamp is " & Format(message, "hh:mm:ss") ' 新增替换代码 c.Text = Format(message, "hh:mm:ss") c.Collapse wdCollapseEnd Debug.Print ' get next timestamp c.Find.Execute Wend Debug.Print "Good bye..." End Sub
内容的提问来源于stack exchange,提问作者historystamp
相关产品推荐
相关产品推荐

