Julius Kaufmann
Julius Kaufmann

Reputation: 11

MS-Word: How to work around oddity in Range.WordOpenXML?

Retrieving the value of property Range.WordOpenXML (VBA, interop) ruins the recording of a custom undo record and also the undo stack:

Public Sub Test()
  Dim xml As String

  ShowState                                       ' 0
  
  Selection.Font.StrikeThrough = wdToggle
  ShowState                                       ' 0
  
  Application.UndoRecord.StartCustomRecord "Foo"
  ShowState                                       ' 1 Foo
  
  Selection.Font.Bold = wdToggle
  ShowState                                       ' 1 Foo
  
  xml = Selection.Range.WordOpenXML
  ShowState                                       ' 1
  
  Selection.Font.Italic = wdToggle
  ShowState                                       ' 1

  Application.UndoRecord.EndCustomRecord
  ShowState                                       ' 0
End Sub

Private Sub ShowState()
  Debug.Print Application.UndoRecord.CustomRecordLevel; _
              Application.UndoRecord.CustomRecordName
End Sub

Consequences of running Test() are:

If you comment out the line toggling the StrikeThrough, things become even more weird:

If, however, you uncomment the line retrieving the WordOpenXML, everything works as expected.

Note: In a VSTO / Interop environment I also had the case that - unlike this example - the CustomRecordLevel was reset to 0 by WordOpenXML.

We'd be grateful for suggestions on how to avoid this odd behaviour or how to work around / correct it.

Best regards,

J.K.

Upvotes: 1

Views: 148

Answers (1)

Stopping then restarting the recording worked for me in VSTO, didn't tried on VBA but something like this should do the trick :

  Dim xml As String
  Dim recordName As String

  recordName = Application.UndoRecord.CustomRecordName
  Application.UndoRecord.EndCustomRecord

  xml = Selection.Range.WordOpenXML

  Application.UndoRecord.StartCustomRecord recordName

After this we still have 1 record

Upvotes: 0

Related Questions