2017-09-27 109 views
0

我得到一个运行时错误91以下的Word VBA:字VBA得到运行时错误91,在Word中使用range.find头

Dim myStoryRange As Object 
    For Each myStoryRange In ActiveDocument.StoryRanges 
    With myStoryRange.find 
     .Text = "test to search" 
     .Replacement.Text = "text to replace" 
     .Wrap = wdFindContinue 
     .ClearFormatting 
     .Replacement.ClearFormatting 
     .Replacement.Highlight = False 
     .Execute replace:=wdReplaceAll 
    End With 
Next myStoryRange 

上一半左右的电脑运行的不一致出现的错误宏。

想法?

每帕特里克的建议,我已经改变了代码如下:

Dim myStoryRange As Range 
For xStories = 1 To ActiveDocument.StoryRanges.Count 

    Set myStoryRange = ActiveDocument.StoryRanges.Item(xStories) 
    With myStoryRange.find 
     .Text = "[Client Name]" 
     .Replacement.Text = Client 
     .Wrap = wdFindContinue 
     .ClearFormatting 
     .Replacement.ClearFormatting 
     .Replacement.Highlight = False 
     .Execute replace:=wdReplaceAll 
    End With 

Next xStories 

这似乎解决了错误91.不过,我仍然得到一个奇怪的结果。此代码在第5行(含myStoryRange.find)失败,集合中的第二个项目出现错误“集合的请求成员不存在”。

存在收集成员时失败。换句话说,有7个xStories,它在xStories = 2时失败。而xStories = 2是一个完整的项目,所有的属性都被引用。

作为供参考,我试图替换文档标题中的一些文本。我在标题中的StoryRange项目上发生故障,而不是文档正文。这可能是问题吗?

+0

我的想法......你还没有包括所有的信息......等等,其行获得误差? – jsotola

+0

难道你不应该'Dim myStoryRange As Range'?您可能必须使用For循环与'ActiveDocument.StoryRanges.Count'和'Set myStoryRange = ActiveDocument.StoryRanges.Item(#)' – PatricK

+0

如果您要替换标题中的文本,为什么不选择您想要的范围像'StoryRanges(wdPrimaryHeaderStory)'而不是循环遍历所有的故事? – xidgel

回答

0

我能解决这个问题(在评论家的帮助下)。答案是标题文本被视为Sections集合中的一个项目。这看起来不一致,因为它在StoryRanges中显示以及项目。但是,使用该集合查找和替换时发生错误。

下面的代码正确地搜索并在Word页眉替换文本:

Dim myStoryRange As Range 

    For xStories = 1 To ActiveDocument.Sections(1).Headers.Count 

     Set myStoryRange = 
     ActiveDocument.Sections(1).Headers.Item(xStories).Range 

     With myStoryRange.find 
      .Text = "[Client Name]" 
      .Replacement.Text = Client 
      .Wrap = wdFindContinue 
      .ClearFormatting 
      .Replacement.ClearFormatting 
      .Replacement.Highlight = False 
      .Execute replace:=wdReplaceAll 
     End With 

    Next xStories