VBA traverses each cell of all Wrod tables and replaces the last two carriage returns in the cell.

1. Traverse

      Iterate through every cell of all tables in word. Because errors often occur when working with cells. A lot of time was wasted.

        

Sub a()
    
    Dim doc As Document, tb As Table, ce As cell
    Dim rng As Range, p As Paragraph
    
    Set doc = ActiveDocument
    
    For Each tb In doc.Tables
        For Each ce In tb.Range.Cells '关键处就是这里一定要用tb.Range.Cells
            '具体处理每个单元格中的东西
            Set p = ce.Range.Paragraphs.Last '单元格最后一个段落
            If Asc(p.Range.Text) = 13 Then '看似没东西,实则若是^13时
                Set p = p.Previous '上一个段落
                If Not p Is Nothing Then '不能为空,表示至少2个段落
                    Set rng = p.Range
                    rng.Collapse wdCollapseEnd
                    rng.MoveEnd wdCharacter, -1
                    rng.Delete
                End If
            End If
        Next
    Next
End Sub

     Note: It must be tb.Range.Cells, otherwise it will be tiring to judge whether to merge horizontal or vertical cells.

2. Two carriage returns

    The cell looks like there are two carriage returns at the end. Use ^p to replace ^p^p, but it has no effect. Then I checked it character by character with VBA. The last two characters that looked like carriage returns were ^13^13, which is vbCr. Replacing ^13^13 with ^13 was invalid. It seems that many years ago, there was a problem with this replacement. , although correct, fails when the last two characters of the cell are replaced.

     Therefore, when working in cells, we generally use the hard keyboard to do it. That is, just use the delete key of the simulated keyboard to do it. Make a judgment that there is such a character (see the code above), then locate it at the end of the paragraph, and delete it directly using the keyboard delete. It really works.

 

Guess you like

Origin blog.csdn.net/dzweather/article/details/132156908