如何使用word vba阅读标题,与文本和形状混合,在最后一页的非常部分?



我刚刚问了一个类似的问题,如何使用word vba读取页眉's文本在最后一页?Macropod提供了一个解决方案,谢谢

然而,如此糟糕,我遇到的文件混合文本和形状的标题,而有用的信息实际上是形状。我做了一个简化版的mix_txt_shape_in_header.docx,并把它放在https://github.com/retsyo/study_vba_doc

对于这个文档,我期望的是在每个部分的最后一页提取所有显示的文本(所以它应该是text + text_in_shape),并提示类似

的内容
Index page i of i
Main part page 2 of 32

在学习了macropod的代码后,我认为如果我可以select头中的形状,我可以读取信息。但很快我遇到了3个问题

  1. 如何select的形状

我记录了一个vba代码,而我在头中操作形状,并发现形状的名称在vba中使用,例如

ActiveDocument.Shapes("TextBox 1").Select

显然,这是不适用的,因为我不能提前知道形状的名字。

连我都知道这个名字并写下

ActiveDocument.Shapes("TextBox 1").TextFrame.TextRange.Text

ActiveDocument.Shapes(1).TextFrame.TextRange.Text

I get error message

invalid use of attribute
  1. 由于我上面所说的原因,我不知道如何获得形状的文本,这是在每个部分的最后一页。这是我所能得到的
Sub getShapeNumber()
NumSections = ActiveDocument.Sections.Count
For idxsec = 1 To NumSections
numShape = ActiveDocument.Sections(idxsec).Headers(wdHeaderFooterPrimary).Shapes.Count
For idxShape = 1 To numShape
txt = "section " & idxsec & ", shape " & numShape & ": "
txt = txt & ActiveDocument.Sections(idxsec).Headers(wdHeaderFooterPrimary).Shapes(idxShape).TextFrame.TextRange.Text
Debug.Print txt
Next
Debug.Print "====="
Next
End Sub

但是它说

section 1, shape 4: 
section 1, shape 4: page i of  i
section 1, shape 4:                          <-- why this shape is here
section 1, shape 4: page 1 of  32            <-- why this shape is here
=====
section 2, shape 4:                          <-- why this shape is here
section 2, shape 4: page i of  i             <-- why this shape is here
section 2, shape 4: 
section 2, shape 4: page 1 of  32
=====

很明显,Sections(idxsec).Headers(wdHeaderFooterPrimary).Shapes不只是在部分中找到形状,另一方面,它在文档

中找到所有形状
  1. 模拟人眼从标题中读取的内容,我必须判断文本或text_in_shape应该放在第一位。但
? ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Shapes(1).left

返回
-999996 

是一个奇怪的坐标数

啊哈,读取头信息是一个繁琐的问题,人们可以阅读。

帮忙吗?谢谢。

  1. 您得到错误,因为您的代码试图访问文档主体中不存在的形状。要访问页眉或页脚中的形状,需要使用类似item 2

    中的代码
  2. 您的代码正在打印标题中形状的总数,而不是形状编号。你的代码应该是:

    Sub getShapeNumber()
    NumSections = ActiveDocument.Sections.Count
    For idxsec = 1 To NumSections
    With ActiveDocument.Sections(idxsec).Headers(wdHeaderFooterPrimary)
    numShape = .Shapes.Count
    For idxShape = 1 To numShape
    txt = "section " & idxsec & ", shape " & idxShape & ": "
    txt = txt & .Shapes(idxShape).TextFrame.TextRange.Text
    Debug.Print txt
    Next
    End With
    Debug.Print "====="
    Next
    End Sub
    

相关内容

最新更新