共用方式為


HOW TO:建立及修改自訂文件屬性

更新: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 屬性將會引發例外狀況。

請參閱

工作

HOW TO:從文件屬性中讀取及寫入

概念

文件層級自訂程式設計