Sub 为所有表格智能添加序号列()
Dim tbl As Table
Dim newCol As Column
Dim i As Long, r As Long
Dim firstColText As String
Dim regEx As Object
Dim isHasSeq As Boolean
Dim processedCount As Integer
Dim skippedCount As Integer
Dim headerName As String
' 初始化正则表达式对象
Set regEx = CreateObject("VBScript.RegExp")
With regEx
.Global = True
.IgnoreCase = True
' 匹配阿拉伯数字、带括号/点/顿号的数字、中文数字开头
' 例如: 1, 1.2, (1), (1), 1., 1、, 一, 二,
.Pattern = "^([\(\(]?[0-9]+[\)\)\.\、\s]?|[一二三四五六七八九十]+[\、\.\s]?)"
End With
' 检查是否有表格
If ActiveDocument.Tables.Count = 0 Then
MsgBox "当前文档中没有表格。", vbInformation
Exit Sub
End If
' 询问用户表头的名称(默认“序号”)
headerName = InputBox("请输入新序号列的表头名称:", "设置表头", "序号")
If StrPtr(headerName) = 0 Then Exit Sub ' 用户点击了取消
If Trim(headerName) = "" Then headerName = "序号" ' 如果用户没填,默认序号
Application.ScreenUpdating = False
Application.DisplayAlerts = False
processedCount = 0
skippedCount = 0
For Each tbl In ActiveDocument.Tables
isHasSeq = False
' --- 1. 判断表内是否已经有序号 ---
' 为了防止空表报错,先检查表格是否有数据
If tbl.Range.Cells.Count > 0 Then
' 提取第一列前3行的内容进行检测(避开可能的合并单元格导致的报错)
Dim checkRows As Integer
checkRows = IIf(tbl.Rows.Count >= 3, 3, tbl.Rows.Count)
For r = 1 To checkRows
firstColText = ""
' 使用上一回教你的防合并报错方式获取第一列文本
On Error Resume Next
firstColText = Trim(tbl.Cell(r, 1).Range.Text)
On Error GoTo 0
' 去掉 Word 单元格特有的换行符和结束符 (Chr(13) & Chr(7))
firstColText = Replace(firstColText, Chr(13) & Chr(7), "")
firstColText = Replace(firstColText, Chr(7), "")
' 如果单元格内匹配到了序号特征
If regEx.Test(firstColText) Then
isHasSeq = True
Exit For
End If
Next r
End If
' --- 2. 根据判断结果执行插入或不插入 ---
If isHasSeq Then
' 判断已有序号,跳过
skippedCount = skippedCount + 1
Else
' 没有序号,执行插入
On Error Resume Next ' 防止遇到极端嵌套表格报错
Set newCol = tbl.Columns.Add(BeforeColumn:=tbl.Columns(1))
On Error GoTo 0
If Not newCol Is Nothing Then
' 设置表头
tbl.Cell(1, 1).Range.Text = headerName
' 自动填充数字(从第2行开始,如果表格只有1行则只填表头)
If tbl.Rows.Count > 1 Then
For i = 2 To tbl.Rows.Count
On Error Resume Next
' 写入行号减一(即 1, 2, 3...)
tbl.Cell(i, 1).Range.Text = CStr(i - 1)
' 顺便让新插入的序号列居中对齐
tbl.Cell(i, 1).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
On Error GoTo 0
Next i
End If
processedCount = processedCount + 1
End If
End If
Next tbl
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "处理完成!" & vbCrLf & _
"成功添加序号列:" & processedCount & " 个表格" & vbCrLf & _
"检测到已有编号,已跳过:" & skippedCount & " 个表格", vbInformation
End Sub
转载自 CSDN-专业IT技术社区
原文链接:https://blog.csdn.net/ducanwang/article/details/171044987



