Vba 将标题内容从.doc复制到.xlsm文件

Vba 将标题内容从.doc复制到.xlsm文件,vba,header,copy,ms-word,Vba,Header,Copy,Ms Word,如何使用VBA将.doc文件的标题复制到工作表中的某些单元格 以下是我能想到的最好的: Sub extract_header() Const wdSeekMainDocument = 0 'this I copied from another code I found Const wdReplaceAll = 2 'but I have no clue if it's usefull or not, I guess not Const wdPrintView = 3

如何使用VBA将.doc文件的标题复制到工作表中的某些单元格

以下是我能想到的最好的:

Sub extract_header()
    Const wdSeekMainDocument = 0 'this I copied from another code I found
    Const wdReplaceAll = 2 'but I have no clue if it's usefull or not, I guess not
    Const wdPrintView = 3
    Const wdSeekCurrentPageHeader = 9
    Const wdSeekCurrentPageFooter = 10
    Path = "C:\Users\guillaume.hebert\Documents\Optimisation\Table des matières\TAB-MAT3.doc" 'define the path
    Set objWord = CreateObject("Word.Application")
    objWord.Documents.Open (Path)
    With objWord.ActiveWindow.ActivePane.View
        .Type = wdPrintView 'change viewing mode
        .SeekView = wdSeekCurrentPageHeader 'open the header
    End With '  now what is the commande I should use to copy the content of the header,
             ' so I can then paste in my excel worksheet, objWord.Header.Copy  ?
End Sub
标题包含如下屏幕截图所示的表格:

我现在收到以下错误消息:


有关如何访问页眉/页脚的基本信息,请参见此处:

注意:这段代码是针对Word的,用Word实现,因此需要对其进行一些修改

Sub EditHeadersAndFooters()

Dim i As Long

For i = 1 To ActiveDocument.Sections.Count
    With ActiveDocument.Sections(i)
        .Headers(wdHeaderFooterPrimary).Range.Text = "Foo"
        .Footers(wdHeaderFooterPrimary).Range.Text = "Bar"
    End With
Next

End Sub
首先,声明变量!objWord在此上下文中显示为未声明,并添加另一个变量来表示使用.open语句打开的文档。这将使您的代码更易读

Sub extract_header()

Const wdSeekMainDocument = 0              'this I copied from another code I found
Const wdReplaceAll = 2                    'but I have no clue if it's usefull or not, I guess not
Const wdPrintView = 3
Const wdSeekCurrentPageHeader = 9
Const wdSeekCurrentPageFooter = 10
Path = "C:\Users\guillaume.hebert\Documents\Optimisation\Table des matières\TAB-MAT3.doc"        'define the path

Dim objWord as Object
Dim doc as Object 'Word.Document
Dim h as Object 'Word.HeaderFooter

Set objWord = CreateObject("Word.Application") 

'## Assign to the DOCUMENT variable:
Set doc = objWord.Documents.Open(Path)

'## Get the primary header from the first section
'   Note: there may be multiple sections, you will need to figure that out on your own
Set h = doc.Sections(1).Headers(wdHeaderFooterPrimary)
h.Range.Select
objWord.Selection.Copy

'Paste the entire table to Excel
Range("A10").Select
Application.CommandBars.ExecuteMso "PasteSourceFormatting"



End Sub

在这一点上,我不确定你需要用它做什么。标题可以包含很多内容,如形状、文本等。因此,下一步要做什么取决于您真正需要提取到Ecxel文件中的内容。

您好,David,谢谢您的回答。我想我已经走到一半了。标题的内容只是放置在表中的文本。因此,我需要的是将Word.doc标题中的所有文本复制到工作簿的特定单元格中。因此,我如何复制和粘贴此内容。请使用标题/表格的屏幕截图更新您的原始问题。将图片上传到imgur.com,并在问题中添加链接,我会看看是否可以提供帮助。我已按要求添加了链接。非常感谢您,我做了一个修订,将整个表格粘贴到Excel。如果你想把所有的值放在一个单元格中,你需要迭代该表并合并字符串值。大卫,你是我的英雄!我刚看到台词排好。。。h、 range.select和objWord.selection.copy。我已经将此添加到代码的其余部分,它的工作非常出色。