处理 Document 对象

   

在 Visual Basic 中,可使用 Document 对象或 Documents 集合对象的方法来修改文件。本主题包含与下列任务相关的 Visual Basic 示例:

新建文档

Documents 集合包含所有打开的文档。若要新建文档,可使用 Add 方法将一个 Document 对象添至 Documents 集合。下列指令新建一篇文档。

Documents.Add

新建文档更好的方法是将返回值赋给一个对象变量。Add 方法返回一个引用新文档的 Document 对象。在下列示例中,将 Add 方法返回的 Document 对象赋给一个对象变量。然后设置该 Document 对象的部分属性和方法。使用对象变量可以很容易地控制新文档。

Sub NewSampleDoc()
    Dim docNew As Document
    Set docNew = Documents.Add
    With docNew
        .Content.Font.Name = "Tahoma"
        .SaveAs FileName:="Sample.doc"
    End With
End Sub

打开文档

若要打开现有的文档,可使用 Documents 集合的 Open 方法。下列指令打开 MyFolder 文件夹中名为 MyDocument.doc 的文档。

Sub OpenDocument()
    Documents.Open FileName:="C:\MyFolder\Sample.doc"
End Sub

保存现有文档

若要保存一篇文档,可使用 Document 对象的 Save 方法。下列指令保存名为 Sales.doc 的文档。

Sub SaveDocument()
    Documents("Sales.doc").Save
End Sub

通过对 Documents 集合应用 Save 方法,可以保存所有打开的文档。下列指令保存所有打开的文档。

Sub SaveAllOpenDocuments()
    Documents.Save
End Sub

保存新文档

若要保存一篇文档,可使用 Document 对象的 SaveAs 方法。下列指令在当前文件夹中保存活动文档,命名为“Temp.doc”。

Sub SaveNewDocument()
    ActiveDocument.SaveAs FileName:="Temp.doc"
End Sub

FileName 参数可以仅包含文件名,也可以包含完整的路径(例如,“C:\Documents\Temporary File.doc”)。

关闭文档

若要关闭一篇文档,可使用 Document 对象的 Close 方法。下列指令关闭并保存名为 Sales.doc 的文档。

Sub CloseDocument()
    Documents("Sales.doc").Close SaveChanges:=wdSaveChanges
End Sub

通过应用 Documents 集合的 Close 方法可关闭所有打开的文档。下列指令在不保存更改的情况下关闭所有的文档。

Sub CloseAllDocuments()
    Documents.Close SaveChanges:=wdDoNotSaveChanges
End Sub

下列示例在文档关闭以前提示用户保存文档。

Sub PromptToSaveAndClose()
    Dim doc As Document
    For Each doc In Documents
        doc.Close SaveChanges:=wdPromptToSaveChanges
    Next
End Sub

激活文档

若要更改活动文档,可使用 Document 对象的 Activate 方法。下列指令激活已打开的名为 Sales.doc 的文档。

Sub ActivateDocument()
    Documents("Sales.doc").Activate
End Sub

确定文档是否已打开

若要确定文档是否处于打开状态,可使用 For Each...Next 语句列举 Documents 集合中的元素。如果文档 Sample.doc 是打开的,则下列示例激活该文档,如果没有打开文档,则将该文档打开。

Sub ActivateOrOpenDocument()
    Dim doc As Document
    Dim docFound As Boolean

    For Each doc In Documents
        If InStr(1, doc.Name, "sample.doc", 1) Then
            doc.Activate
            docFound = True
            Exit For
        Else
            docFound = False
        End If
    Next doc

    If docFound = False Then Documents.Open FileName:="Sample.doc"
End Sub

引用活动文档

与通过名称或索引序号引用文档不同(例如 Documents("Sales.doc")),ActiveDocument 属性返回一个引用活动文档(具有焦点的文档)的 Document 对象。下列示例显示活动文档的名称,或在没有打开的文档时显示一条消息。

Sub ActiveDocumentName()
    If Documents.Count >= 1 Then
        MsgBox ActiveDocument.Name
    Else
        MsgBox "No documents are open"
    End If
End Sub