Skip to main content
 首页 » 编程设计

c#之在线程中调用互操作 Excel 函数时出现 CastError

2024年02月20日18EasonJim

我有一个具有此功能的 excel 插件类:

public void testRibbon() 
{ 
     Excel.Workbook workbook = this.Application.ActiveWorkbook;       
     Excel.Worksheet activeSheet = workbook.Sheets[1]; 
     Excel.Range range = activeSheet.get_Range(JOB_ID_FIELD + HEADER_ROW, TOTAL_STATUS_PERCENTAGE_KEY_FIELD + (10 + 1).ToString()); 
     range.get_Range("C4").Value = "test Ribbon complete"; 
} 

在功能区中,我添加了一个按钮,按下该按钮将在线程中调用 testRibbon:

private void process_Click(object sender, RibbonControlEventArgs e) 
{ 
    Thread processThread = new Thread(delegate(){ 
        Globals.ExcelAddin.testRibbon(); 
    }); 
    processThread.Start(); 
}  

这会导致转换错误:

Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel._Workbook'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208DA-0000-0000-C000-000000000046}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).

如果我不使用新线程,则不会发生转换错误。

编辑:尝试使用任务工厂,同样的错误:

var task2 = Task.Factory.StartNew( 
() => 
{ 
     Globals.BobStats.testRibbon(); 
}); 

请您参考如下方法:

在 Excel 中使用多线程毫无意义,因为 Excel 的 COM 接口(interface)基本上是单线程的(参见 article)。加载项中可能会有更多限制。

但我不得不说我并不真正理解错误消息的意思。