使用 Microsoft Word VBA - 将前导零添加到日期的宏
Working with Microsoft Word VBA - macro to add leading zeroes to date
我正在尝试使用 VBA 在 Microsoft Word 2013 中创建一个宏,以将前导零添加到日期(主要是日期和月份)
所以从 4/6/2004 到 04/06/2004
以及 5/11/2005 至 05/11/2005
我尝试在这里使用答案的变体,但它在第一次约会时无限循环:http://answers.microsoft.com/en-us/office/forum/office_2010-word/macro-to-convert-date-format-in-a-document/20539af7-a961-499f-9e85-22af8f4c3c58?auth=1
Sub ConvertDateFormat()
Dim FoundOne As Boolean
Selection.HomeKey Unit:=wdStory, Extend:=wdMove
FoundOne = True ' loop at least once
Do While FoundOne ' loop until no date is found
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([0-9]{1,2})[/]([0-9]{1,2})[/]([0-9]{4})"
.Format = True
.Forward = True
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceNone
' check that the find is a date
If IsDate(Selection.Text) Then
Selection.Text = Format(Selection.Text, "dd/mm/yyyy")
Selection.Collapse wdCollapseEnd
Else ' not a date - end loop
FoundOne = False
End If
Loop
End Sub
试试这个并了解我所做的更改。
MS-word 查找和替换的艺术在于范围、折叠和循环(for 和 do while)
在 Win-7pro、64、office 2010、32 上工作正常
Sub ConvertDateFormat()
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([0-9]{1,2})[/]([0-9]{1,2})[/]([0-9]{4})"
.Format = True
.Wrap = wdFindStop
.Forward = True
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
If IsDate(.Text) Then
.Text = Format(.Text, "dd/mm/yyyy")
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End Sub
我正在尝试使用 VBA 在 Microsoft Word 2013 中创建一个宏,以将前导零添加到日期(主要是日期和月份)
所以从 4/6/2004 到 04/06/2004 以及 5/11/2005 至 05/11/2005
我尝试在这里使用答案的变体,但它在第一次约会时无限循环:http://answers.microsoft.com/en-us/office/forum/office_2010-word/macro-to-convert-date-format-in-a-document/20539af7-a961-499f-9e85-22af8f4c3c58?auth=1
Sub ConvertDateFormat()
Dim FoundOne As Boolean
Selection.HomeKey Unit:=wdStory, Extend:=wdMove
FoundOne = True ' loop at least once
Do While FoundOne ' loop until no date is found
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([0-9]{1,2})[/]([0-9]{1,2})[/]([0-9]{4})"
.Format = True
.Forward = True
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceNone
' check that the find is a date
If IsDate(Selection.Text) Then
Selection.Text = Format(Selection.Text, "dd/mm/yyyy")
Selection.Collapse wdCollapseEnd
Else ' not a date - end loop
FoundOne = False
End If
Loop
End Sub
试试这个并了解我所做的更改。
MS-word 查找和替换的艺术在于范围、折叠和循环(for 和 do while)
在 Win-7pro、64、office 2010、32 上工作正常
Sub ConvertDateFormat()
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([0-9]{1,2})[/]([0-9]{1,2})[/]([0-9]{4})"
.Format = True
.Wrap = wdFindStop
.Forward = True
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
If IsDate(.Text) Then
.Text = Format(.Text, "dd/mm/yyyy")
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End Sub