|
楼主 |
发表于 2020-7-17 11:58
|
显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
这个程序好,解决了问题。
Sub test()
Dim mh, reg
Set reg = CreateObject("VBScript.RegExp")
With reg
.Pattern = "第[零一二三四五六七八九十百千万]*条"
.Global = True
End With
Set mh = reg.Execute(ActiveDocument.Content)
For Each mhk In mh
With ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.Forward = True
.Text = mhk
.Replacement.Text = "第" & toNum1(toNumBZH(Mid(mhk, 2, Len(mhk) - 2))) & "条" '替换字符串
.Execute Replace:=wdReplaceAll
End With
Next
End Sub
Private Function toNumBZH(mystr As String) As String '此函数将输入的中文数字(允许大写、小写、数字、西文空格混编,如有其它字符出现则输出为空串)
Dim i%, k%, k1%, myPos1%
Dim str1$, comString$
comString = "一壹二贰三叁四肆五伍六陆七柒八捌九玖零〇十拾百佰千仟万萬亿億兆0123456789"
mystr = Replace(mystr, " ", "")
mystr = Replace(mystr, "貳", "2")
mystr = Replace(mystr, "陸", "6")
mystr = Replace(mystr, "两", "2")
For i = 1 To Len(mystr)
str1 = Mid(mystr, i, 1)
myPos1 = InStr(1, comString, str1, vbBinaryCompare)
If myPos1 = 0 Then Exit Function
Select Case myPos1
Case 1 To 18
mystr = Replace(mystr, str1, Trim(str(Int((myPos1 + 1) / 2))))
Case 19, 20
mystr = Replace(mystr, str1, "0")
Case 22, 24, 26, 28, 30
mystr = Replace(mystr, str1, Mid(comString, myPos1 - 1, 1))
End Select
Next
For i = 1 To Len(mystr)
str1 = Mid(mystr, i, 1)
myPos1 = InStr(1, comString, str1, vbBinaryCompare)
If myPos1 >= 21 And myPos1 <= 31 Then k1 = i
If str1 = "0" Then
k = InStr(1, comString, Mid(mystr, i + 1, 1), vbBinaryCompare)
If k >= 21 And k <= 31 And Val(Mid(mystr, k1 + 1, i - k1)) = 0 Then mystr = Left$(mystr, i - 1) & "1" & Right$(mystr, Len(mystr) - i)
End If
Next
toNumBZH = mystr
End Function
Private Function toNum1(mystr As String) As Double 'mystr 数据已经经过toNumBZH函数处理
Dim i As Integer, myPos1 As Integer, myPos2%, falg% 'falg标志最高位在字串中出现位置,myPos2 表示最高位次数
Dim str1 As String
Dim comString As String
comString = "十百千万┩兆╊亿0123456789" '加入┩╊为处理方便,如在有可能出现的场合可先清除
If mystr = "" Then
toNum1 = 0
Exit Function
End If
myPos2 = 0
falg = 0
For i = 1 To Len(mystr)
str1 = Mid(mystr, i, 1)
myPos1 = InStr(1, comString, str1, vbBinaryCompare)
Select Case myPos1
Case 1 To 8
If myPos1 >= myPos2 Then
falg = i
myPos2 = myPos1
End If
End Select
Next
Select Case falg
Case 0 '代表字串为纯数字
Dim mynum As Long
For i = Len(mystr) To 1 Step -1
mynum = mynum + Val(Mid(mystr, i, 1)) * 10 ^ (Len(mystr) - i)
Next
toNum1 = mynum
Exit Function
Case 1 '万三千....
toNum1 = toNum1(Right(mystr, Len(mystr) - falg)) + 10 ^ (myPos2)
Case 2
Dim temp As String
temp = Mid(mystr, 1, 1)
If InStr(1, comString, temp, vbBinaryCompare) > 8 Then '代表第一位为数字第二位为位符如6万
toNum1 = toNum1(Right(mystr, Len(mystr) - falg)) + Val(temp) * 10 ^ (myPos2)
Else '如十万、百万...万万
toNum1 = toNum1(Right(mystr, Len(mystr) - falg)) + 10 ^ (InStr(1, comString, temp, vbBinaryCompare) + myPos2)
End If
Case Else
toNum1 = toNum1(Right(mystr, Len(mystr) - falg)) + toNum1(Left(mystr, falg - 1)) * 10 ^ (myPos2)
End Select
End Function |
|