我希望能够识别两个互操作变量对象何时引用相同的“实际”对象。例如,所谓“实际”,是指Microsoft Word文档中给定的段落或脚注。
vb中的示例:(注意,c#答案也可以,问题是与无关的语言)
Imports Microsoft.Office.Interop
Sub Tests()
Dim WordApp as Word.Application = Globals.ThisAddIn.Application
Dim ThisDoc as Word.Document = WordApp.ActiveDocument
Dim ThisSelection As Word.Selection = ThisDoc .Application.Selection
If ThisSelection.Range Is Nothing Then Exit Sub
Dim SelectedPara As Word.Paragraph = ThisSelection.Range.Paragraphs.First
For Each MyPara As Word.Paragraph In ThisDoc.Paragraphs
'Reference equality: Never finds a match
If MyPara.Equals(SelectedPara) Then MsgBox("Paragraph Found by ref")
'Property equality: Seems to works ok with .ParaID
If MyPara.ParaID = SelectedPara.ParaID Then MsgBox("Paragraph Found by Id")
Next
End Sub如您所见,通过引用比较对象变量不起作用。虽然这有点令人沮丧,但如果.ParaID没有说得那么少的话,我可以在文档属性上运行比较器:
保留给内部使用。
欢迎在以下方面发表任何评论:(1)如何避免使用.ParaID;(2)使用.ParaID作为唯一标识符的可靠性(有关此属性的任何信息也是受欢迎的,因为微软和谷歌对该主题保持沉默)。
这个问题也可以推广到其他集合,如Word.Footnotes、Word.Bookmarks。我想Excel.Worksheets也会发生同样的情况,等等。
发布于 2019-06-21 20:37:08
在Word中可以通过多种方式来实现这一点。一种比较直接的方法是使用Range方法比较InRange属性。例如:
Sub Tests()
Dim WordApp as Word.Application = Globals.ThisAddIn.Application
Dim ThisDoc as Word.Document = WordApp.ActiveDocument
Dim ThisSelection As Word.Selection = WordApp.Selection
If ThisSelection.Range Is Nothing Then Exit Sub
Dim SelectedPara As Word.Range = ThisSelection.Range.Paragraphs.First.Range
For Each MyPara As Word.Paragraph In ThisDoc.Paragraphs
Dim rng as Word.Range = myPara.Range
If rng.InRange(SelectedPara) And SelectedPara.InRange(rng) Then
'They're the same
Else
'They're not the same
End If
rng = Nothing
Next
End Subhttps://stackoverflow.com/questions/56702772
复制相似问题