我有一个代码可以与选定的运行文本一起使用,但不能与选定的表格单元格一起使用。
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
我也有提取每个单元格值的代码,但是如何修改它以便在选定的表单元格上运行。 第一个代码:
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
答案 0 :(得分:0)
这是您应该能够适应您的目的的代码。
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