如何:从文档属性中读取或向文档属性写入
更新:2007 年 11 月
适用对象 |
---|
本主题中的信息仅适用于指定的 Visual Studio Tools for Office 项目和 Microsoft Office 版本。 项目类型
Microsoft Office 版本
有关更多信息,请参见 按应用程序和项目类型提供的功能。 |
您可以将文档属性随文档或工作簿一起存储在 Microsoft Office Word 和 Microsoft Office Excel 的文档级自定义项中。Excel 和 Word 都提供了很多内置属性,如 Author、Title 和 Subject。
在 Excel 中设置文档属性
使用 ThisWorkbook 类的 BuiltinDocumentProperties 属性处理内置属性。此属性返回一个 DocumentProperties 对象,该对象是 DocumentProperty 对象的集合。您可以使用该集合的 Item 属性,按名称或按索引检索该集合中的特定属性。
更改 Excel 中的 Revision Number 属性
将内置文档属性赋给一个变量。
Dim properties As Microsoft.Office.Core.DocumentProperties properties = DirectCast(Globals.ThisWorkbook.BuiltinDocumentProperties, _ Microsoft.Office.Core.DocumentProperties) Dim prop As Microsoft.Office.Core.DocumentProperty prop = properties.Item("Revision Number")
Microsoft.Office.Core.DocumentProperties properties; properties = (Microsoft.Office.Core.DocumentProperties) Globals.ThisWorkbook.BuiltinDocumentProperties; Microsoft.Office.Core.DocumentProperty prop; prop = properties["Revision Number"];
将 Revision Number 属性增加 1。
If prop.Value Is Nothing Then prop.Value = 1 Else Dim revision As Integer If Integer.TryParse(prop.Value.ToString(), revision) Then prop.Value = revision + 1 MessageBox.Show("Revision Number = " & revision) Else MessageBox.Show("Revision Number = invalid value") End If End If
if (prop.Value == null) { prop.Value = 1; } else { int revision; if (int.TryParse((string)prop.Value, out revision)) { prop.Value = revision + 1; MessageBox.Show("Revision Number = " + revision); } else { MessageBox.Show("Revision Number = invalid value"); } }
在 Word 中设置文档属性
使用 ThisDocument 类的 BuiltInDocumentProperties 属性处理内置属性。此属性返回一个 DocumentProperties 对象,该对象是 DocumentProperty 对象的集合。您可以使用该集合的 Item 属性,按名称或按索引检索该集合中的特定属性。
更改 Subject 属性
将内置文档属性赋给一个变量。
Dim properties As Microsoft.Office.Core.DocumentProperties properties = DirectCast(Globals.ThisDocument.BuiltInDocumentProperties, _ Microsoft.Office.Core.DocumentProperties)
Microsoft.Office.Core.DocumentProperties properties; properties = (Microsoft.Office.Core.DocumentProperties) Globals.ThisDocument.BuiltInDocumentProperties;
将 Subject 属性更改为“Whitepaper”。
' Set the Subject property. properties.Item("Subject").Value = "Whitepaper"
// Set the Subject property. properties["Subject"].Value = "Whitepaper";
可靠编程
这些示例假定您已经在 Excel 的 ThisWorkbook 类中和 Word 的 ThisDocument 类中编写了代码。
尽管您使用的是 Word 和 Excel 及其对象,但 Microsoft Office 提供了可用的内置文档属性的列表。尝试访问未定义的属性的 Value 属性会引发异常。