首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在循环中创建活动文档?

在循环中创建活动文档?
EN

Stack Overflow用户
提问于 2016-02-08 19:21:05
回答 1查看 49关注 0票数 1

我试图从多个文档中拉出一个段落,通过让sub解析每个文档来查找总是在两个术语之间的段落。但是我不能让"activedocument“或打开的文档工作吗?以前我可以很好地使用open函数,但现在每次都会收到对象错误。文件夹目录和文件名由用户输入到单独的单元格中,因此单元格中的文本必须组合在一起才能形成完整的文档地址。以下是代码

代码语言:javascript
复制
Sub findTest()

    Dim firstTerm As String, filename As Variant
    Dim secondTerm As String, J As Integer
    Dim myRange As Range
    Dim documentText As String
    Dim mydoc As String
    Dim file As Variant


    Dim startPos As Long 'Stores the starting position of firstTerm
    Dim stopPos As Long 'Stores the starting position of secondTerm based on first term's location
    Dim nextPosition As Long 'The next position to search for the firstTerm
J = 2
nextPosition = 1
Do Until J > 600



    Documents.Open filename:="Worksheets(1).Cells(5, 5) & Worksheets(2).Cells(J, 1)", ReadOnly:=True ' I get an error here every single time.


    'First and Second terms as defined by your example.  Obviously, this will have to be more dynamic

    firstTerm = "<firstword>"
    secondTerm = "<secondname>"

    'Get all the document text and store it in a variable.
    Set myRange = ActiveDocument.Range
    'Maximum limit of a string is 2 billion characters.
    'So, hopefully your document is not bigger than that.  However, expect declining performance based on how big doucment is
    documentText = myRange.Text

    'Loop documentText till you can't find any more matching "terms"
    Do Until nextPosition = 0
        startPos = InStr(nextPosition, documentText, firstTerm, vbTextCompare)
        stopPos = InStr(startPos, documentText, secondTerm, vbTextCompare)
        Debug.Print Mid$(documentText, startPos + Len(firstTerm), stopPos - startPos - Len(secondTerm))
        nextPosition = InStr(stopPos, documentText, firstTerm, vbTextCompare)
    Loop
   J = J + 1
   file = Dir
   Close Document
Loop

End Sub
EN

回答 1

Stack Overflow用户

发布于 2016-02-09 02:55:31

不要依赖ActiveDocument。声明一个Word.Document对象,并将打开的文档分配给该对象。然后使用该对象而不是ActiveDocument -更可靠!

代码语言:javascript
复制
Dim oDoc as Word.Document
Set oDoc = Documents.Open(filename)
Dim oRng as Word.Range
Set oRng = oDoc.Content 
'Preferred over oDoc.Range for getting content of entire document
oDoc.Close

注意:我不知道你想用Close Document做什么,这可能是你的问题的一部分?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35268425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档