vba Word如何在表中获取句子



我有一个Word文档,前两个句子为普通文本,第三句和第四句在一个表格中(在一个单元格中):

My first sentence. My second sentence.
My third sentence. My fourth sentence.
我的代码如下:
Option Explicit
Sub test()
Dim sentence As Variant
Dim i As Long: i = 0

Selection.Expand wdSentence
Debug.Print "--------->" & ActiveDocument.ActiveWindow.Selection.Sentences.Count
Debug.Print "selection: " & ActiveDocument.ActiveWindow.Selection
For Each sentence In ActiveDocument.ActiveWindow.Selection.Sentences
i = i + 1
Debug.Print i & " sentence: " & sentence
Next
End Sub

如果我选择前两句,调试输出是正确的:

--------->2
selection: My first sentence. My second sentence.

1 sentence: My first sentence. 
2 sentence: My second sentence.

如果我选择表中的两个句子,调试输出是奇怪的(或错误的?):

--------->2
selection: My third sentence. My fourth sentence.
1 sentence: My third sentence. 

为什么表内容的输出与正常文本不同?如何获得与普通文本相同的表内容结果?

表格为Word识别的句子带来了另一个完整的复杂性。段落、单元格结束标记和行结束标记都会混淆VBA的句子组成。

这里是一些应该工作的代码,但我不能100%肯定地说它将在所有情况下工作。换句话说,我知道它可以改进,但它应该为您自己的调试会话提供一个良好的开端。

Sub ParseBySentence()
Dim doc As Word.Document
Dim i As Long, s As Long, para As Word.Paragraph
Dim rng As Word.Range, sRng As Word.Range

Application.ScreenUpdating = False
On Error Resume Next
Set doc = ActiveDocument
For i = 1 To doc.Paragraphs.Count
Set para = doc.Paragraphs(i)
If para.Range.Information(wdWithInTable) Then
Set rng = para.Range
Do While Asc(rng.Characters.Last) = 13
rng.MoveEnd unit:=wdCharacter, Count:=-1
Loop
If rng.Text = vbNullString Or _
Asc(rng.Text) = 13 Then
'do nothing
Else
For s = 1 To rng.Sentences.Count
Set sRng = rng.Sentences(s)
Do While Asc(sRng.Characters.Last) = 13
sRng.MoveEnd unit:=wdCharacter, Count:=-1
Loop
sRng.Select
Debug.Print Selection.Text
Selection.Collapse Word.WdCollapseDirection.wdCollapseEnd
Next
End If
End If
Next
Selection.HomeKey unit:=wdStory
Application.ScreenUpdating = True
MsgBox "Action Complete"
End Sub

@Rich Michaels:谢谢你的段落提示。我做了一个快速和简约的宏,也可以在表中工作:

Sub Par2Sen()
Dim s0, s1, smax As Long
Dim para As Word.Paragraph
Dim r() As Byte
For Each para In ActiveDocument.Paragraphs
r = para.Range
Debug.Print "> Paragraph= " & para.Range;
smax = UBound(r) - 1
s0 = 0
s1 = 0
Do Until s1 > smax
If r(s1) = 46 Or s1 = smax Then
Debug.Print "-> Sen from" & (s0 / 2) + 1 & " to " & (s1 / 2) + 1 & MidB$(r, s0 + 1, s1 - s0 + 3)
s0 = s1 + 2
End If
s1 = s1 + 2
Loop
Next
End Sub