本帖最后由 守候_CJ 于 2023-2-20 20:58 编辑
Word VBA:判断一个单元格是否为合并单元格 一、代码
- Function 是合并单元格(myCell As Cell) As String
- Dim results(1 To 3) As Variant
- Dim tb As Table
- Dim maxRow As Long
- Dim maxCol As Long
- Dim nextCell As Cell
- Dim i As Long
- Dim 有合并行 As Boolean: 有合并行 = False
- Dim 合并行数 As Long: 合并行数 = 0
- Dim 有合并列 As Boolean: 有合列行 = False
- Dim 合并列数 As Long: 合并列数 = 0
-
- Set tb = myCell.Range.Tables(1)
- maxRow = tb.Rows.count
- maxCol = tb.Columns.count
-
- On Error Resume Next
- For i = myCell.RowIndex + 1 To maxRow
- Set nextCell = tb.Cell(i, myCell.ColumnIndex)
- Do While Err.Number = 5941
- If i > maxRow Then
- Exit Do
- End If
- Err.Clear
- i = i + 1
- Set nextCell = tb.Cell(i, myCell.ColumnIndex)
- Loop
-
- 合并行数 = i - myCell.RowIndex
- If 合并行数 > 1 Then
- 有合并行 = True
- End If
- Exit For
- Next
-
- For i = myCell.ColumnIndex + 1 To maxCol
- Set nextCell = tb.Cell(myCell.RowIndex, i)
- Do While Err.Number = 5941
- If i > maxCol Then
- Exit Do
- End If
- Err.Clear
- i = i + 1
- Set nextCell = tb.Cell(myCell.RowIndex, i)
- Loop
-
- 合并列数 = i - myCell.ColumnIndex
- If 合并列数 > 1 Then
- 有合并列 = True
- End If
- Exit For
- Next
- On Error GoTo 0
-
- results(1) = 有合并行 Or 有合并列
- results(2) = 合并行数
- results(3) = 合并列数
-
- 是合并单元格 = VBA.Join(results, ";")
- End Function
复制代码
二、说明函数返回结果格式为: True;2;1 以分号(;)为标志,分为3部分: 第一部分,表明是否为合并单元格(True是,False否); 第二部分,合并行的数值,比如2表示此单元格合并了2行; 第三部分,合并列的数值,比如1表示此单元格合并了1列(1列即没有合并列)。
|