设置WORD表格中数字的千分位格式

时间:2022-08-26 19:30:31 阅读: 最新文章 文档下载
说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

设置WORD表格中数字的千分位格式

守柔的经典代码里有一个是批量设置千分位格式的,如下

Sub 批量设置千分位格式()

Dim myRange As Range

Dim myValue As Double

Application.ScreenUpdating = False

Do '进入一个循环

'定义myRange为活动文档的主文字部分

Set myRange = ActiveDocument.Content

With myRange.Find

.ClearFormatting

.Text = "[0-9]{4,}[!年]"

.MatchWildcards = True

If .Execute = False Then Exit Do '如果没找到则退出循环

myValue = Val(myRange.Text) '取得数字

myRange.SetRange myRange.Start, myRange.End - 1 '重新定义myRange对象

myRange.Text = VBA.Format$(myValue, "#,###") '写入千分位格式

End With

Loop

Application.ScreenUpdating = True

End Sub

但对含有表格的数字无效,依据此代码,绕了个弯,写了个可以替换表格中数字的千分位格式的代码,请指正。

Sub SetThousands()

Dim theTB As Table

Dim theCell As Cell

Dim sText As String

Dim RegEx As Object

Dim RegMatchCollection As Object

Set RegEx = CreateObject("vbscript.regexp")

With RegEx

.Global = True

.IgnoreCase = True

.Pattern = "[0-9]{4,}" '[!年]"

End With

Set theTB = ActiveDocument.Tables(1)

For Each theCell In theTB.Range.Cells

sText = VBA.Replace(theCell.Range.Text, Chr(13), "")

sText = VBA.Replace(sText, Chr(7), "")

Set RegMatchCollection = RegEx.Execute(sText)

If RegMatchCollection.Count > 0 Then

theCell.Range.SetRange theCell.Range.Start, theCell.Range.End - 1

theCell.Range.Text = VBA.Format$(sText, "#,###")

End If

Next

End Sub

#Vba

本文来源:https://www.wddqw.com/doc/e368d04c69eae009581bec75.html