Created
May 20, 2026 06:34
-
-
Save SomeBottle/e52b3feea8eb73eefb885c5bd83fd14e to your computer and use it in GitHub Desktop.
Word 参考文献列表引用 [1][2][3] 转换为 [1-3] 格式的宏
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Sub MergeConsecutiveCrossReferences() | |
| Dim flds As Fields | |
| Set flds = Selection.Fields | |
| ' 1. 检查选区内是否有足够的域 | |
| If flds.Count < 2 Then | |
| MsgBox "请先用鼠标选中需要合并的连续交叉引用(例如选中 [1][2][3])。", vbExclamation, "提示" | |
| Exit Sub | |
| End If | |
| Dim firstFld As Field | |
| Dim lastFld As Field | |
| Set firstFld = flds(1) | |
| Set lastFld = flds(flds.Count) | |
| ' 2. 验证选中的是否为 REF 域(交叉引用) | |
| If InStr(1, firstFld.Code.Text, "REF", vbTextCompare) = 0 Or _ | |
| InStr(1, lastFld.Code.Text, "REF", vbTextCompare) = 0 Then | |
| MsgBox "选中的内容不包含有效的交叉引用域,请重新选择。", vbExclamation, "提示" | |
| Exit Sub | |
| End If | |
| ' 关闭屏幕刷新以提高运行效率 | |
| Application.ScreenUpdating = False | |
| Dim firstCode As String, lastCode As String | |
| Dim pos As Long | |
| ' 3. 处理第一个域:清除旧格式开关,添加 \#"[0" | |
| firstCode = firstFld.Code.Text | |
| pos = InStr(1, firstCode, "\#") | |
| If pos > 0 Then firstCode = Left(firstCode, pos - 1) ' 清除可能已存在的数字格式开关 | |
| firstCode = Replace(firstCode, "\* MERGEFORMAT", "", , , vbTextCompare) ' 移除多余的保留格式开关 | |
| firstFld.Code.Text = Trim(firstCode) & " \# ""[0""" | |
| ' 4. 处理最后一个域:清除旧格式开关,添加 \#"0]" | |
| lastCode = lastFld.Code.Text | |
| pos = InStr(1, lastCode, "\#") | |
| If pos > 0 Then lastCode = Left(lastCode, pos - 1) | |
| lastCode = Replace(lastCode, "\* MERGEFORMAT", "", , , vbTextCompare) | |
| lastFld.Code.Text = Trim(lastCode) & " \# ""0]""" | |
| ' 5. 从后往前删除中间所有的多余交叉引用域 | |
| Dim i As Long | |
| For i = flds.Count - 1 To 2 Step -1 | |
| flds(i).Delete | |
| Next i | |
| ' 6. 在第一个域后面精准插入连接符 "-" | |
| firstFld.Select | |
| Selection.Collapse wdCollapseEnd | |
| Selection.Text = "-" | |
| ' 7. 刷新首尾域,更新页面显示 | |
| firstFld.Update | |
| lastFld.Update | |
| ' 恢复屏幕刷新 | |
| Application.ScreenUpdating = True | |
| End Sub |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment