Runtime COMException Unhandeled

夙愿已清 提交于 2019-12-13 03:39:06

问题


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?


回答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

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 and interior) is Nothing 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



来源:https://stackoverflow.com/questions/7081960/runtime-comexception-unhandeled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!