![将 MS Word 中的段落计数转换为可用于循环的变量](https://linux22.com/image/1361529/%E5%B0%86%20MS%20Word%20%E4%B8%AD%E7%9A%84%E6%AE%B5%E8%90%BD%E8%AE%A1%E6%95%B0%E8%BD%AC%E6%8D%A2%E4%B8%BA%E5%8F%AF%E7%94%A8%E4%BA%8E%E5%BE%AA%E7%8E%AF%E7%9A%84%E5%8F%98%E9%87%8F.png)
我有一个宏,它从文档 A 中提取选定数量的文本,将其粘贴到文档 B 中,轮询 Word 以获取文档 B 中的段落总数,然后对文档 B 中的文本执行例程,当例程完成后,将修改后的文本复制回文档 A。执行此操作时,它会在文档中留下 AI 想要删除的文本残余。(宏的相关部分发布如下)宏确定段落数,然后根据文档 B 中的段落数删除文档 A 中的一定数量的表格行。我在线收到错误,这让我很困惑。我的代码有什么问题?
Sub info3()
Selection.WholeStory
Dim k As Integer
Dim AD As Document
Dim DP As Object
Set AD = ActiveDocument
Set DP = AD.BuiltInDocumentProperties
' Returns the number of paragraphs and lines in a document.
MsgBox "There are " & DP("Number Of Paragraphs") & _
" paragraphs containing text " & "and " & DP("Number Of Lines") & _
" lines counted."
'top of page
Selection.HomeKey Unit:=wdStory
'remove a row from a table an amount of times determined by # of paragraphs
' if 8 paragraphs detected, do this procedure 4 times.
'following line gets an error statement. Why?
Do Until k > (DP / 2)
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Rows.Delete
k = k + 1
Loop
End Sub
答案1
DP 是一个对象,而不是数字,所以你不能除以 2。你需要将段落数存储在一个新变量中
Dim numParagraphs as Integer
numParagraphs = DP("Number Paragraphs")
并在循环中使用它。
此外,您还混合了表格和文本属性。行是表属性,您需要在表内才能删除行。此外,您必须使用索引来访问特定行。例如
Selection.Rows(1).Delete
您可以使用以下命令清除选定的文本:
Selection.Text = ""
但我不知道这是否是您想要实现的。
答案2
MS 网站上的一位评论者帮助我解决了这个问题......
Dim k As Integer
Dim AD As Document
Dim DP As Object
Dim LP As Long
Set AD = ActiveDocument
Set DP = AD.BuiltInDocumentProperties
LP = DP("Number Of Paragraphs") / 2
Selection.HomeKey Unit:=wdStory
' if 8 paragraphs detected, do this procedure 4 times.
Do Until k > LP
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Rows.Delete
k = k + 1
Loop
End Sub