如何在 Ms Word 中使用宏反转仅选定 table 单元格的单词

How to Reverse the words of only selected table cells using macro in Ms Word

我有一个代码适用于选定的运行宁文本,但不适用于选定的[=28] =] 细胞。

Dim i As Integer
Dim oWords As Words
Dim oWord As Range
Set oWords = Selection.Range.Words
For i = 1 To oWords.Count Step 1

    Set oWord = oWords(i)

    ''Make sure the word range doesn't include a space
    Do While oWord.Characters.Last.text = " "
        Call oWord.MoveEnd(WdUnits.wdCharacter, -1)
    Loop

    Debug.Print "'" & oWord.text & "'"
    oWord.text = StrReverse(oWord.text)

Next i

我也有提取每个单元格值的代码,但如何在选定的 table 单元格上将其修改为 运行。 第一个代码:

Sub Demo()
Dim x As String
Dim i As Integer
Dim j As Integer
Dim Tbl As Table
Set Tbl = ActiveDocument.Tables(1)
  For i = 1 To Tbl.Rows.Count
        For j = 1 To Tbl.Columns.Count
        x = Tbl.Cell(i, j).Range.Text
Next j
  Next i
End Sub

第二个密码:

Sub testTable()
Dim arr As Variant
Dim intcols As Integer
Dim lngRows As Long
Dim lngCounter As Long

lngRows = ActiveDocument.Tables(1).Rows.Count
intcols = ActiveDocument.Tables(1).Columns.Count
arr = Split(Replace(ActiveDocument.Tables(1).Range.Text, Chr(7), ""), Chr(13))
For rw = 1 To lngRows
    For col = 1 To intcols
        Debug.Print "Table 1, Row " & rw & ", column " & col; " data is " & arr(lngCounter)
        lngCounter = lngCounter + 1
    Next
    lngCounter = lngCounter + 1
Next
End Sub

这是您应该能够适应您的目的的代码。

Sub FindWordsInTableCells()
    Dim doc As Word.Document, rng As Word.Range
    Dim tbl As Word.Table, rw As Word.Row, cl As Word.Cell
    Dim i As Integer, iRng As Word.Range
    Set doc = ActiveDocument
    For Each tbl In doc.Tables
        For Each rw In tbl.rows
            For Each cl In rw.Cells
                Set rng = cl.Range
                rng.MoveEnd Word.WdUnits.wdCharacter, Count:=-1
                For i = 1 To rng.words.Count
                    Set iRng = rng.words(i)
                    Debug.Print iRng.Text
                Next i
            Next cl
        Next rw
    Next tbl
End Sub

如果您只想使用当前选中的单元格,则使用上述例程的改编版。

Sub FindWordsInSelectedTableCells()
    Dim rng As Word.Range
    Dim cl As Word.Cell
    Dim i As Integer, iRng As Word.Range
    If Selection.Information(wdWithInTable) = True Then
        For Each cl In Selection.Cells
            Set rng = cl.Range
            rng.MoveEnd Word.WdUnits.wdCharacter, Count:=-1
            For i = 1 To rng.words.Count
                Set iRng = rng.words(i)
                rng.Select
                'insert your word manipulation code here
                Debug.Print Selection.Text
            Next i
        Next cl
    End If
End Sub