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?
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 Nothingto check for that. Also, you’ve already set up theForloop 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 + 1which 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
Objectwhich 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,lRangeandinterior) isNothingat 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