如何使用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
标题包含一个表格,如下面的屏幕截图所示:
我现在收到此错误消息:
答案 0 :(得分:0)
请参阅此处了解如何访问页眉/页脚的基础知识:
WORD 2010 Macro for Editing Headers & Footers
注意:此代码适用于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
在此上下文中显示为未声明)并添加另一个变量来表示您使用Document
语句打开的.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文件中的内容。