我将一个单元格值复制到另一个Excel单元格。第一个单元格包含F列值的总和,因此它是一个公式单元格。这是我发送到另一个Excel单元格。 我之前在range.copy()方法上工作过。有时它有效,有些时候不起作用。我收到了这个错误:
未处理的类型' System.Runtime.InteropServices.COMException'发生在mscorlib.dll
附加信息:Range类的复制方法失败
private void Form1_Load(object sender, EventArgs e)
{
xlApp = new ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkBook = xlApp.Workbooks.Open(@"C:\\1\\2\\900styles.xls", 0,
false, 5, "", "", false, XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);
cellsRange11 = xlWorkSheet.UsedRange.Cells;
columnRange11 = cellsRange11.Columns;
rowRange11 = cellsRange11.Rows;
numberOfColumns11 = columnRange11.Count;
numberOfRows11 = rowRange11.Count;
xlApp1 = new ApplicationClass();
xlWorkBook1 = xlApp1.Workbooks.Add(misValue);
xlWorkBook1 = xlApp1.Workbooks.Open(@"C:\\1\\2\\900soloro.xls", 0,
false, 5, "", "", false, XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
Worksheet xlWorkSheet1 = (Worksheet)xlWorkBook1.Worksheets.get_Item(1);
cellsRange12 = xlWorkSheet1.UsedRange.Cells;
columnRange12 = cellsRange12.Columns;
rowRange12 = cellsRange12.Rows;
numberOfColumns12 = columnRange12.Count;
numberOfRows12 = rowRange12.Count;
xlApp2 = new ApplicationClass();
xlWorkBook2 = xlApp2.Workbooks.Add(misValue);
xlWorkBook2 = xlApp2.Workbooks.Open(@"C:\\1\\2\\12_week_sum.xls", 0,
false, 5, "", "", false, XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
Worksheet xlWorkSheet2 = (Worksheet)xlWorkBook2.Worksheets.get_Item(1);
cellsRange13 = xlWorkSheet2.UsedRange.Cells;
columnRange13 = cellsRange13.Columns;
rowRange13 = cellsRange13.Rows;
numberOfColumns13 = columnRange13.Count;
numberOfRows13 = rowRange13.Count;
Range R1 = xlWorkSheet.get_Range("F944", "F944");
Range R2 = xlWorkSheet2.get_Range("C7", "C7");
R1.Copy(R2);
xlApp.ActiveWorkbook.Saved = true;
xlApp1.ActiveWorkbook.Saved = true;
xlApp2.ActiveWorkbook.Saved = true;
xlWorkBook2.SaveCopyAs("C:\\1\\2\\12_week_summary_" + DateTime.Now.ToString("MMddyy") + ".xls");
xlWorkBook2.Close(true, "C:\\1\\2\\12_week_sum.xls", null);
xlWorkBook1.Close(true, "C:\\1\\2\\900soloro.xls", null);
xlWorkBook.Close(true, "C:\\1\\2\\C:\\1\\2\\900styles.xls", null);
xlWorkBook2.Close(true, "C:\\1\\2\\12_week_summary_" + DateTime.Now.ToString("MMddyy") + ".xls", null);
xlApp.Quit();xlApp1.Quit();xlApp2.Quit();
releaseObject(xlApp);releaseObject(xlApp1);releaseObject(xlApp2);
releaseObject(xlWorkBook); releaseObject(xlWorkBook1); releaseObject(xlWorkBook2);
releaseObject(xlWorkSheet);releaseObject(xlWorkSheet1);releaseObject(xlWorkSheet2);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}