2017-03-01 115 views
0

previously asked a question哪些未得到答复。我想在这里重振一下,或许更简单一点,希望我能回答这个问题。超出范围输入字段在Word页脚VBA

我需要更改超过500个文档页脚的格式,并且不想手动完成。 我在一个空白文档中记录了一个宏,对其进行了修改以清理它并且不使用选择属性:它工作得很好。一旦我将该代码块复制/粘贴到我现有的代码中,并且我在需要更改的文档上尝试了该代码块,则根本无法再插入这些字段,并且收到“4608值超出范围”错误。如果我将我的ran1变量标注为Range,则在范围的定义中出现类型不匹配。 我想获得一些帮助,让字段实际插入页脚。

下面是我目前使用的代码:

Sub EnterFieldInFooter() 

Dim wor As Object 
Dim fso As Object 
Dim fol As Object 
Dim fil As Object 
Dim doc As Object 

Set fso = CreateObject("Scripting.FileSystemObject") 
Set fol = fso.GetFolder("M:\test") 

Dim ran1 As Object 

i = 3 

Set wor = CreateObject("word.application") 

For Each fil In fol.Files 

    If Right(fil.Name, 4) = ".doc" Or Right(fil.Name, 5) = ".docx" And Left(fil.Name, 2) <> "~$" Then 
     ' open the document 
     Set doc = wor.documents.Open(Filename:=fil.Path) 

     Set ran1= doc.sections.first.footers(1).Range 'footer range 

     ' Set qualifying statement 
     ran1.Text = "This is an uncontrolled document when printed or saved. " & _ 
        "See online database for most recent version." 
     ' Enter the last saved date 
     ran1.InsertAfter (vbCrLf & "Save Date: ") 
     ran1.Collapse Direction:=wdCollapseEnd 
     Set ran1 = doc.sections.first.footers(1).Range 
     ran1.Fields.Add Range:=ran1, Type:=wdFieldEmpty, Text:="SAVEDATE \@ ""yyyy/MM/dd""", PreserveFormatting:=True 
     ' Enter the last printed date 
     Set ran1 = doc.sections.first.footers(1).Range 
     ran1.InsertAfter (vbTab & "Print Date: ") 
     ran1.Collapse Direction:=wdCollapseEnd 
     ran1.Fields.Add Range:=ran1, Type:=wdFieldEmpty, Text:="PRINTDATE \@ ""yyyy/MM/dd""", PreserveFormatting:=True 

     ' Save updated file 
     pat = "M:\test1" & "\" & fil.name 
     doc.saveas pat 

    End If 

Next 

End Sub 
+0

你可以尝试'设置RAN1 = doc.StoryRanges(wdPrimaryFooterStory)' – Slai

+0

@Slai当我使用的是,它告诉我收集的请求的成员不存在 – Jodi

回答

0

,因为你需要提供节号看到的错误可能发生。试试这个:

Set ran1 = doc.Sections(1).Footers(wdHeaderFooterPrimary).Range 
ran1.Text = "This is an uncontrolled document when printed or saved. " & _ 
       "See online database for most recent version." 
ran1.InsertAfter (vbCrLf & "Save Date: ") 
ran1.Collapse Direction:=wdCollapseEnd 
ran1.fields.Add Range:=ran1, Type:=wdFieldEmpty, Text:="SAVEDATE \@ ""yyyy/MM/dd""", PreserveFormatting:=True 
Set ran1 = doc.Sections(1).Footers(wdHeaderFooterPrimary).Range 
ran1.InsertAfter (vbTab & "Print Date: ") 
ran1.Collapse Direction:=wdCollapseEnd 
ran1.fields.Add Range:=ran1, Type:=wdFieldEmpty, Text:="PRINTDATE \@ ""yyyy/MM/dd""", PreserveFormatting:=True 

根据您的文档结构,您可能需要使用#章节(#)乱动,并用wdHeaderFooterPrimarywdHeaderFooterPrimary

希望帮助

+0

我的版本的VBA不会让我用'wdHeaderFooterPrimary'字符串来引用页脚,我必须使用'Sections(1).Footers(1)',否则我会收到一个错误,告诉我该集合的成员不存在 – Jodi

+0

好奇你正在使用什么版本的VBA。在“工具”|“引用”中是否选择了对“Microsoft Word ##。#Object Library”的引用?这就是'wdHeaderFooterPrimary'的定义。第(1)节有帮助吗? – xidgel

+0

哦,我的天啊,我已经完成了如此简单的文档编辑工作,只启用了Excel对象库而没有问题,我没有考虑启用Word库。为了好奇,我一直在Office 2010中使用VBA。非常感谢您的提醒! – Jodi