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

更新:2007 年 11 月

适用对象

本主题中的信息仅适用于指定的 Visual Studio Tools for Office 项目和 Microsoft Office 版本。

项目类型

  • 文档级项目

Microsoft Office 版本

  • 2007 Microsoft Office system

  • Microsoft Office 2003

有关更多信息,请参见按应用程序和项目类型提供的功能

Microsoft Office Excel 和 Microsoft Office Word 提供与工作簿和文档一起存储的内置属性。此外,如果要将其他信息与文档级自定义项中的文档一起存储,可以创建和修改自定义文档属性。

请将 CustomDocumentProperties 属性与自定义属性一起使用。此属性返回一个 DocumentProperties 对象,该对象是 DocumentProperty 对象的集合。您可以使用该集合的 Item 属性,按名称或按索引检索该集合中的特定属性。

下面的示例演示如何在 Excel 中添加一个自定义属性,并为该属性赋值。

示例

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", missing);
}

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 属性会引发异常。

请参见

任务

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

概念

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