我有这种语法,不会抛出任何错误,看起来它是正确的代码。但是,不添加总行数。我的语法有什么不对?
if (xlApp.WorksheetFunction.CountA(WS.Cells) != 0)
{
lastRow = WS.Cells.Find("*", WS.Range["A1"], Excel.XlFindLookIn.xlFormulas, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false).Row;
}
else { lastRow = 1; }
WS.Range["C" + lastRow + 1].FormulaR1C1 = "=SUM(R[-" + lastRow + "]C:R[-1]C)";
WS.Range["C" + (lastRow + 1) + ":N" + (lastRow + 1)].FillRight();
WS.Range["N" + lastRow + 1].FillRight();
修改
我也尝试使用下面的Special Cells
语法,结果相同,没有错误,但是我的任何工作表都没有添加总行
Excel.Range MyLast = WS.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range MyRange = WS.get_Range("A1", MyLast);
int MyLastRow = MyLast.Row;
int MyLastColumn = MyLast.Column;
WS.Range["A" + MyLastRow + 1].FormulaR1C1 = "Totals:";
WS.Range["C" + MyLastRow + 1].FormulaR1C1 = "=SUM(R[-" + lastRow + "]C:R[-1]C)";
WS.Range["C" + (MyLastRow + 1) + ":N" + (lastRow + 1)].FillRight();
WS.Range["N" + MyLastRow + 1].FillRight();
答案 0 :(得分:1)
我不确定这对您是否有帮助,但是如果您想获得所用行的总和,并且如果您的数据之间没有空行,那么就不会这样做。是否更容易使用countif配方?找到你的第一个空单元格,然后在那个单元格中(动态地)插入countif公式?
有点像
xl.Range LastCell = YourSheet.Cells.SpecialCells(xl.XlCellType.xlCellTypeLastCell, Type.Missing);
xl.Range MyLastCellInSpecificColumn = YourSheet.get_Range("A1", LastCell );
MyLastCellInSpecificColumn.Formula = "=COUNTIF('YourSheet'!A1:A5000,\"<>\"&\"\")";
这会计算您的行数,并显示最后一个单元格中总行数。 同样,我不确定这会对您的特定任务有所帮助,但我想为什么不尝试并提供帮助。
答案 1 :(得分:0)
我会使用“SpecialCells”会员(?),这是一个例子:
using System;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelDemo
{
class Core
{
public static void Main(string[] args)
{
Excel.Application MyExcel = new Excel.Application();
// MyExcel.Visible = false;
Excel.Workbook MyWorkbook = null;
object Missing = System.Reflection.Missing.Value;
MyWorkbook = MyExcel.Workbooks.Open("C:\\Temp\\Document.xlsx");
Excel.Sheets MySheets = MyWorkbook.Worksheets;
Excel.Worksheet MyWorksheet = (Excel.Worksheet)MySheets.get_Item("Tabelle1");
Excel.Range MyLast = MyWorksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
int MyLastRow = MyLast.Row;
int MyLastColumn = MyLast.Column;
// MyLast.Insert(Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing);
Excel.Range MyLine = (Excel.Range)MyWorksheet.Rows[MyLastRow]; // Row Index
MyLine.Insert();
MyWorksheet.SaveAs("C:\\Temp\\Document_Edited.xlsx");
MyWorkbook.Close(false, Missing, Missing);
MyExcel.Quit();
}
}
}