如何:创建和修改自定义文档属性

上面列出的 Microsoft Office 应用程序提供与文档一起存储的内置属性。此外,如果要将其他信息与文档一起存储,可以创建和修改自定义文档属性。

**适用于:**本主题中的信息适用于以下应用程序的文档级项目和应用程序级项目:Excel 2013 和 Excel 2010;PowerPoint 2013 和 PowerPoint 2010;Project 2013 和 Project 2010;Word 2013 和 Word 2010。有关更多信息,请参见按 Office 应用程序和项目类型提供的功能

请将文档的 CustomDocumentProperties 属性与自定义属性一起使用。例如,在 Microsoft Office Excel 的文档级项目中,请使用 ThisWorkbook 类的 CustomDocumentProperties 属性。在 Excel 的应用程序级项目中,请使用 Microsoft.Office.Interop.Excel.Workbook 对象的 CustomDocumentProperties 属性。这些属性返回一个 DocumentProperties 对象,该对象是 DocumentProperty 对象的集合。您可以使用该集合的 Item 属性,按名称或按索引检索该集合中的特定属性。

下面的示例演示在 Excel 文档级自定义项中,如何添加自定义属性并为其赋值。

链接到视频 有关相关的视频演示,请参见 How Do I: Access and Manipulate Custom Document Properties in Microsoft Word?(如何实现:在 Microsoft Word 中访问和操作自定义文档属性。)

示例

Sub TestProperties()
    Dim properties As Microsoft.Office.Core.DocumentProperties
    properties = CType(Me.CustomDocumentProperties, Office.DocumentProperties)

    If ReadDocumentProperty("Project Name") <> Nothing Then
        properties("Project Name").Delete()
    End If

    properties.Add("Project Name", False, _
        Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString, _
        "White Papers")
End Sub

Private Function ReadDocumentProperty(ByVal propertyName As String) As String
    Dim properties As Office.DocumentProperties
    properties = CType(Me.CustomDocumentProperties, Office.DocumentProperties)

    Dim prop As Office.DocumentProperty

    For Each prop In properties
        If prop.Name = propertyName Then
            Return prop.Value.ToString()
        End If
    Next

    Return Nothing
End Function
void TestProperties()
{
    Microsoft.Office.Core.DocumentProperties properties;
    properties = (Office.DocumentProperties)this.CustomDocumentProperties;

    if (ReadDocumentProperty("Project Name") != null)
    {
        properties["Project Name"].Delete();
    }

    properties.Add("Project Name", false,
        Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,
        "White Papers");
}

private string ReadDocumentProperty(string propertyName)
{
    Office.DocumentProperties properties;
    properties = (Office.DocumentProperties)this.CustomDocumentProperties;

    foreach (Office.DocumentProperty prop in properties)
    {
        if (prop.Name == propertyName)
        {
            return prop.Value.ToString();
        }
    }
    return null;
}

可靠编程

尝试访问未定义的属性的 Value 属性会引发异常。

请参见

任务

如何:从文档属性中读取或向文档属性写入

其他资源

应用程序级外接程序编程

对文档级自定义项进行编程