运行时 COMException 未处理 [英] Runtime COMException Unhandeled
问题描述
我正在开发一款可写入 Excel 的应用.下面的 f 代码工作正常(它填充了请求的单元格),但生成了一个我无法摆脱的运行时异常.
I'm working on an app that writes to excel. The following piece f code is working properly ( it fills the requested cell) but generating a run time exception that I can't get rid of.
For i = 1 To 1000 Step 1
If Not (cPart.Range("A" & i).Value = Nothing) Then
If (cPart.Range("L" & i).Value = Nothing) Then
cPart.Range("L" & i).Interior.ColorIndex = 3
End If
i = i + 1
End If
Next
异常是:COMException 未处理:来自 HRESULT 的异常:0x800A01A8
the exception is: COMException was unhandled :Exception from HRESULT: 0x800A01A8
有什么帮助吗?
推荐答案
HRESULT 的意思是Object Required
.因此,您尝试操作的一个或多个对象似乎不存在,但由于目前编写的代码,很难确定它是哪个.不过,一个紧迫的问题是您将值与 Nothing
进行比较,在 VB.Net 中,您应该使用 Is Nothing
来检查它.此外,您已经将 For
循环设置为从 1 到 1000,步长为 1(您不需要包含,因为它是默认值),但是您正在执行i = i + 1
看起来是个错误?
That HRESULT means Object Required
. So it seems like one or more of the objects you try to operate on don't exist but as the code is written at the moment, it's difficult to be sure which it is. An immediate concern though is that you're comparing values to Nothing
, in VB.Net you're supposed to use Is Nothing
to check for that. Also, you've already set up the For
loop to go from 1 to 1000, with a step of 1 (which you don't need to include since it's the default) but you're then doing i = i + 1
which looks like a mistake?
因此,修复它并将其拆分为多个部分,可能会让您更好地了解哪些不起作用:
So fixing that and splitting it up into it's parts it might give you a better idea to what's not working:
For i = 1 To 1000
Dim aRange As Object = cPart.Range("A" & i)
If aRange IsNot Nothing AndAlso aRange.Value IsNot Nothing Then
Dim lRange As Object = cPart.Range("L" & i)
If lRange IsNot Nothing AndAlso lRange.Value Is Nothing Then
Dim interior As Object = lRange.Interior
If interior IsNot Nothing Then
interior.ColorIndex = 3
End If
End If
End If
Next
我已将新对象声明为 Object
,可能需要将其更改为正确的数据类型(取决于您的项目设置).
I've declared the new objects as Object
which might need to be changed to the correct data types (depending on your project settings).
希望您现在应该能够毫无错误地运行代码,并且您还应该能够单步执行代码并找到新对象之一(aRange
、lRange
和 interior
) 是 Nothing
在某些时候它不应该是它会告诉你为什么它之前抛出那个错误.
Hopefully you should now be able to run through the code without error and you should also be able to step through the code and find that one of the new objects (aRange
, lRange
and interior
) is Nothing
at some point when it shouldn't be which will show you why it threw that error before.
像这样拆分代码的另一个优点是,您现在可以正确处理 Excel 对象,以便 Excel 实例可以完全关闭.有关信息,请参阅此问答:Excel.Range 对象未处理因此未关闭 Excel 进程
Another advantage to splitting up the code like this is that you'll now be able to dispose of the Excel objects properly so that the Excel instance can shut down cleanly. See this Q&A for info: Excel.Range object not disposing so not Closing the Excel process
这篇关于运行时 COMException 未处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!