|
本帖最后由 守候_CJ 于 2023-3-2 22:53 编辑
Word VBA:用FormatNumber()函数对数字格式进行替换
自定义函数代码
- Function 数字格式替换(Optional 范围 As Range, Optional findText As String = "[0-9]{1,}", Optional 使用通配符 As Boolean = True, Optional 小数位数 As Long = -1, Optional 纯小数补零 As VbTriState = VbTriState.vbUseDefault, Optional 负数加括号 As VbTriState = VbTriState.vbUseDefault, Optional 加千分位 As VbTriState = VbTriState.vbUseDefault) As Long
- Dim pd As Boolean: pd = True
- Dim arr() As Range
- Dim i As Long: i = 0
- Dim s As String
- Dim r As String
-
- If fw Is Nothing Then
- pd = False
- Set fw = Selection.Range
- If fw.Start = fw.End Then
- Set fw = ActiveDocument.Range
- End If
- End If
-
- With fw.Find
- .ClearFormatting
- .Wrap = wdFindStop
- .Forward = True
- .MatchWildcards = 使用通配符
- .Text = findText
- Do While .Execute
- i = i + 1
- ReDim Preserve arr(1 To i)
- Set arr(i) = fw.Document.Range(fw.Start, fw.End)
- 'arr(i).Select
- 'Debug.Print fw.Text, fw.Start, fw.End
- Loop
- End With
-
- For i = UBound(arr) To LBound(arr) Step -1
- s = arr(i).Text
- r = s
- If IsNumeric(r) Then
- r = FormatNumber(s, 小数位数, 纯小数补零, 负数加括号, 加千分位)
- End If
- arr(i).Text = r
- 'arr(i).Select
- Next i
-
- 数字格式替换 = UBound(arr) - LBound(arr) + 1
-
- Erase arr
- If pd = False Then
- fw.Select
- Set fw = Nothing
- End If
- End Function
- Sub 数字格式替换程序入口()
- Dim i As Long
- i = 数字格式替换(findText:="[0-9]{5,}", 小数位数:=2)
- MsgBox "完成,共替换了" & i & "处数字格式。"
- End Sub
复制代码
光标定位在主程序内运行即可
|
|