我最近也有这样的需求,让AI帮我写了一个,初步测试好像没问题
Sub ReplaceChineseWithArabic() Dim wdDoc As Object Set wdDoc = ActiveDocument ' 使用正则表达式查找所有“第X条”格式并进行替换 With CreateObject("VBScript.RegExp") .Global = True .IgnoreCase = True .Pattern = "第([\u4e00-\u9fa5]+)条" Dim matches As Object, match As Object If .Test(wdDoc.Content.Text) Then Set matches = .Execute(wdDoc.Content.Text) Dim replacements As Object Set replacements = CreateObject("Scripting.Dictionary") For Each match In matches Dim chineseNumeral As String chineseNumeral = match.SubMatches(0) ' 如果是汉字数字,则进行转换 Dim arabicNumeral As String arabicNumeral = ChineseToArabic(chineseNumeral) ' 记录需要替换的内容 replacements(match.Value) = "第" & arabicNumeral & "条" Next match ' 批量替换 Dim key As Variant For Each key In replacements.Keys wdDoc.Content.Find.Execute FindText:=key, ReplaceWith:=replacements(key), Replace:=2 ' wdReplaceAll = 2 Next key End If End With MsgBox "汉字数字已全部替换为阿拉伯数字!" ' 清理 Set wdDoc = NothingEnd Sub' 函数:将汉字数字转换为阿拉伯数字Function ChineseToArabic(chineseNumeral As String) As String Dim chineseNumerals As Object Set chineseNumerals = CreateObject("Scripting.Dictionary") chineseNumerals.Add "零", 0 chineseNumerals.Add "一", 1 chineseNumerals.Add "二", 2 chineseNumerals.Add "三", 3 chineseNumerals.Add "四", 4 chineseNumerals.Add "五", 5 chineseNumerals.Add "六", 6 chineseNumerals.Add "七", 7 chineseNumerals.Add "八", 8 chineseNumerals.Add "九", 9 chineseNumerals.Add "十", 10 chineseNumerals.Add "百", 100 chineseNumerals.Add "千", 1000 chineseNumerals.Add "万", 10000 Dim result As Integer Dim temp As Integer Dim unit As Integer Dim prevUnit As Integer Dim i As Integer Dim ch As String result = 0 temp = 0 unit = 1 For i = Len(chineseNumeral) To 1 Step -1 ch = Mid(chineseNumeral, i, 1) If chineseNumerals.exists(ch) Then If chineseNumerals(ch) >= 10 Then If chineseNumerals(ch) > prevUnit Then unit = chineseNumerals(ch) temp = 0 Else temp = temp * chineseNumerals(ch) unit = chineseNumerals(ch) End If Else temp = temp + chineseNumerals(ch) result = result + temp * unit temp = 0 unit = 1 End If prevUnit = chineseNumerals(ch) End If Next i ' 处理最后的单位 If temp > 0 Then result = result + temp * unit End If ChineseToArabic = CStr(result)End Function