运行时 COMException 未处理
我正在开发一个可以写入 Excel 的应用程序。下面的 f 代码工作正常(它填充了请求的单元格),但生成了一个我无法摆脱的运行时异常。
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
有帮助吗?
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
the exception is: COMException was unhandled :Exception from HRESULT: 0x800A01A8
any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该 HRESULT 表示
需要对象
。因此,您尝试操作的一个或多个对象似乎不存在,但由于目前编写了代码,因此很难确定它是哪个。不过,迫在眉睫的问题是您正在将值与Nothing
进行比较,在 VB.Net 中,您应该使用Is Nothing
来检查这一点。另外,您已经将For
循环设置为从 1 到 1000,步长为 1(您不需要包含它,因为它是默认值),但您接下来要做的i = i + 1
这看起来像是一个错误?因此,解决这个问题并将其分成几个部分可能会让您更好地了解哪些部分不起作用:
我已将新对象声明为
Object
,它可能需要更改为正确的数据类型(取决于您的项目设置)。希望您现在应该能够毫无错误地运行代码,并且还应该能够单步执行代码并找到新对象之一(
aRange
、lRange
和interior
) 在某些不应该是Nothing
的时候会告诉你为什么它之前抛出了这个错误。像这样拆分代码的另一个优点是,您现在可以正确处理 Excel 对象,以便 Excel 实例可以干净地关闭。有关信息,请参阅此问答:Excel.Range 对象未处理,因此未关闭 Excel 进程
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 toNothing
, in VB.Net you're supposed to useIs Nothing
to check for that. Also, you've already set up theFor
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 doingi = 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:
I've declared the new objects as
Object
which might need to be changed to the correct data types (depending on your project settings).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
andinterior
) isNothing
at some point when it shouldn't be which will show you why it threw that error before.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