我正在尝试解决某些使用MS Office Interop库的VB NET代码中的不一致问题。使用相同的文件和数据运行,以下代码将引发此异常:
指定集合的索引超出范围。
在System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode,IntPtr errorInfo)
在System.Runtime.InteropServices.CustomMarshalers.EnumeratorViewOfEnumVariant.MoveNext()
位于path \ file.vb中的myProject.TableNotePages(clsUsrDoc&usrdoc):行1454
...
第1454行是iShp + = 1行
Dim MyDoc As Word.Document = usrdoc.Document
Dim NoteBoxes As New Collections.Generic.SortedDictionary(Of Integer, Word.TextFrame)
Dim iShp As Integer = 1
For Each shp As Word.Shape In MyDoc.Sections.First.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Shapes
If Not shp.TextFrame.Next Is Nothing Then
NoteBoxes.Add(iShp, shp.TextFrame)
iShp += 1
End If
Next
有一些问题可以帮助我解决这个问题:
任何对这里可能发生的情况的见识都将受到赞赏。
答案 0 :(得分:0)
vb / word互操作似乎偶尔会走出shapes集合的结尾。下面的代码将“ for each”替换为“ for x to y”,在几种环境中成功运行了统计上可观的次数(大约50次)。我知道这不是一个很好的答案,仍然不能回答为什么会发生这种问题,但是确实可以解决问题,因此在有示例帮助其他人的情况下发布作为答案:
Dim MyDoc As Word.Document = usrdoc.Document
Dim NoteBoxes As New Collections.Generic.SortedDictionary(Of Integer, Word.TextFrame)
Dim iShp As Integer = 1
Dim loopLength As Integer = MyDoc.Sections.First.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Shapes.Count
Dim shp As Word.Shape = Nothing
For i As Integer = 1 To loopLength '1-indexed
shp = MyDoc.Sections.First.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Shapes(i)
If Not shp.TextFrame.Next Is Nothing Then
NoteBoxes.Add(iShp, shp.TextFrame)
iShp += 1
End If
Next