Excel interop - Problem with recalculating the specific range
Here's the current code I have got
private void recalculateRRange(Excel.Range UsedRange)
{
Excel.Range currentRRange = null, firstRRange = null;
currentRRange = (Excel.Range)UsedRange.Find("#HERE#", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing);
while (currentRRange != null)
{
if (firstRRange == null)
{
开发者_StackOverflow firstRRange = currentRRange;
}
else if (currentRRange.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing) == firstRRange.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing))
{
break;
}
//force current range to recalculate
currentRRange.Calculate();
currentRRange = (Excel.Range)UsedRange.FindNext(currentRRange);
}
}
The above method is used to find the cells that marked as #HERE#
and to force this cell to recalculate so we can get the updated results.
I managed to get this code working a day ago but somehow it's not working now. I guess that code is somewhat buggy anyway as I have been able to capture the exception just one time. I wonder if there's any better way to implement it?
Exception captured:
Exception from HRESULT: 0x800AC472
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Range.Calculate()
I don't know whether or not it meant something. My best guess is that probably something prevents currentRRange
from calling Calculate()
.
The error you get means VBA_E_IGNORE
which in turn means that something/someone is running/interacting on that sheet... this could be a user and/or some complex calculation.
You should set Visible = false
on the Excel application object and wait a little while after selecting the Range
and retry the Calculate
call when you receive this error...
Another point: you should avoid accessing the Excel application object from multiple threads.
精彩评论