You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.Net中设置/编辑/删除Word自定义文档属性

Word VBA迁移至VB.Net(.Net Framework 4.8.1)自定义文档属性处理问题

我正在将旧版Word VBA应用迁移到VB.Net(WinForms/.Net Framework 4.8.1),大部分功能已实现,但在处理Word文档自定义文档属性时遇到了问题。

原VBA代码

ActiveDocument.CustomDocumentProperties.Add Name:="mc_ver", LinkToContent:=False, Type:=msoPropertyTypeNumber, Value:=0
ActiveDocument.CustomDocumentProperties("mc_ver").Value = 1
ActiveDocument.CustomDocumentProperties("mc_ver").Delete

我的VB.Net简化代码

Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Word
'Imports Microsoft.Office.Core
....
Try
  wordApp = New Word.Application ' CreateObject("Word.Application")
  oDoc = wordApp.Documents.Open(FileName:=someFile)
  With oDoc
    Dim cdps = .CustomDocumentProperties
    Try
      cdps("mc_ver").delete 'works
    Catch ex As Exception
    End Try
    Try
      'cdps.add("mc_ver", "0")
      '=============================
      ' the .add method produces the following error
      ' The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
      ' The following works!
      '=============================
      Dim typeDocCustomProps As Type = cdps.[GetType]()
      Dim oArgs As Object() = {"mc_ver", False, 1, 0}
      ' The following works
      typeDocCustomProps.InvokeMember("Add", BindingFlags.[Default] Or BindingFlags.InvokeMethod, Nothing, cdps, oArgs)
    Catch ex As Exception
    End Try
    For Each prop In .CustomDocumentProperties
      Try
        If prop.Name = "mc_ver" Then prop.Value = prop.Value + 2 'works
      Catch ex As Exception
        Console.WriteLine(ex.Message)
        End Try
    Next
    '=============================
    ' add character at the begining of the doc and then delete it
    ' to be able to save the document?!
    .Range(0, 0).Select()
    .Application.Selection.TypeText("1")
    .Application.Selection.HomeKey(Word.WdUnits.wdStory, Word.WdMovementType.wdMove)
    .Application.Selection.Characters(1).Delete()
    .Save()
    .Close(False)
  End With
Catch ex As Exception
  Console.WriteLine(ex.Message)
  MsgBox(ex.Message)
End Try

问题与解决过程

  • 最初无法正常操作自定义文档属性集合,网上多数示例涉及Microsoft.Office.Core,但无法确认其使用方式,怀疑它是ActiveX类型而非程序集,仅适用于VSTO应用。
  • 编辑更新:已实现自定义属性的编辑、删除功能,但发现Word COM对象需要文档内容有改动才能保存,这和桌面版Word的行为不同。不过添加自定义属性的问题仍未解决。
  • 最新更新:通过反射调用的方法,已成功解决添加自定义属性的问题。

内容的提问来源于stack exchange,提问作者rtO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:43:20