У меня такое ощущение, что этот вопрос очень простой, но я просто не могу найти ответ.
Я хочу применить столбец формул в столбце "C" на основе информации в столбцах "A" и "B". Я хочу, чтобы формула работала так же, как и в Excel, когда вы пишете формулу, а затем перетаскиваете ее, создавая относительные по строкам формулы вниз.
Приведенный ниже метод работает, но он очень медленный, поскольку он записывает каждую формулу отдельно. Я уверен, что где-то есть более эффективный метод.
Спасибо
using Excel = Microsoft.Office.Interop.Excel;
...
object oOpt = System.Reflection.Missing.Value; //for optional arguments
Excel.Application oXL = null;
Excel.Workbook oWB = null;
Excel.Worksheet oSheet = null;
Excel.Range oRng = null;
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel.Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
...
//Set numberOfRows
//Load information to column A and B
...
//Write the column of formulas
for (int r = 2; r < numberOfRows + 2; r++)
{
oRng = oSheet.get_Range("C" + r, "C" + r);
oRng.Formula = "= IF(AND(A" + r + "<> 0,B" + r + "<>2),\"YES\",\"NO\")";
}
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
finally
{
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(oRng);
Marshal.FinalReleaseComObject(oSheet);
oWB.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(oWB);
oXL.Quit();
Marshal.FinalReleaseComObject(oXL);
}