代码的第一部分:
activeWorksheet = Globals.ThisAddIn.Application.ActiveSheet;
var allWorksheets = new List<Worksheet>();
这就是我正在测试的内容:
allWorksheets.Add(activeWorksheet);
Debug.WriteLine(activeWorksheet.Name); //prints Sheet1
Debug.WriteLine(allWorksheets[0].Name); //prints Sheet1
Debug.WriteLine(allWorksheets[0] == activeWorksheet); //prints true
当我在后台运行此任务时,它不起作用。当我执行最后一次比较时它返回false
,即使它打印Sheet1和Sheet1。
new Task(() =>
{
allWorksheets.Add(activeWorksheet);
Debug.WriteLine(activeWorksheet.Name); //prints Sheet1
Debug.WriteLine(allWorksheets[0].Name); //prints Sheet1
Debug.WriteLine(allWorksheets[0] == activeWorksheet); //prints false
}
Excel中的工作表是否存在一些奇怪的背景行为?我暂时使用工作表名称进行比较,但这不应该有效吗?
答案 0 :(得分:1)
我有类似的问题。我为Interop.Excel.Worksheet
创建了一个包装器对象,并实现了这个等于方法:
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, Worksheet)
If other Is Nothing Then Return False
Return ParentsAreEqual(other) AndAlso _worksheet.Name.Equals(other._worksheet.Name)
End Function
Private Function ParentsAreEqual(other As Worksheet) As Boolean
Dim result As Boolean
Try
result = _worksheet.Parent.Equals(other._worksheet.Parent)
Catch ex As Exception
result = False
End Try
Return result
End Function
Public Overrides Function GetHashCode() As Integer
Try
Return _worksheet.Parent.GetHashCode() Xor _worksheet.Name.GetHashCode
Catch ex As Exception
Return 42
End Try
End Function
答案 1 :(得分:1)
您还可以通过检查工作簿名称来概括对象比较。否则,如果两个打开的工作簿具有相同的工作表名称,则可能会得到错误的结果。一个简单的功能如下:
Function Worksheet_is_worksheet(sh1 As Worksheet, sh2 As Worksheet) As Boolean
'Function to circumvent (known but unresolved) issues with object comparison for
'worksheets
Worksheet_is_worksheet = (sh.Name = sh2.Name) And _
(sh.Parent.Name = sh2.Parent.Name)
End Function