在 excel 中的最后一列之前删除

Delete before last column in excel

此代码将删除最后一列。它工作正常:

Microsoft.Office.Interop.Excel.Range last = xlWorkSheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);      
last.EntireColumn.Delete(Missing.Value);

但是,如果我将上面的代码与下面的代码结合起来:

Microsoft.Office.Interop.Excel.Range last1 = xlWorkSheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
last1.EntireColumn.Delete(Missing.Value);

..合并的代码将删除 1 列而不是两列。为什么?

我的逻辑是,如果我删除最后一列,然后尝试再次获取新的 LastCell 并删除,它将删除 2,但由于某种原因没有发生。

我认为你应该只使用 For Loop 来删除你想要的列数。 像这样的东西:

for (int i = 0; i < 2; i++)
{
  last.EntireColumn.Delete(Missing.Value);
}

尚未对此进行测试,但希望它能起作用 :) 你明白了

这是因为 xlCellTypeLastCell 的值将保持不变 直到工作簿关闭并重新打开 (它可以通过编程方式重置。请参阅"update" 部分)。您可以通过检查 last1.Column 的值来确保这一点,您会注意到它与 last.Column.

相同

这种行为也可以在 Excel 本身中手动观察到。尝试在 Excel 中手动删除列 ,然后按 Ctrl+End。您会注意到激活的单元格仍在空列中。 xlCellTypeLastCell 所做的是模仿 Ctrl+End.

的行为

相反,您可以使用其他方法来获取上次使用的列。这样的事情应该有效:

首先,在文件顶部添加这一行以简化命名空间:

using MSOffice = Microsoft.Office.Interop;

那么你可以这样做:

MSOffice.Excel.Range last = 
    xlWorkSheet.Cells.Find(What: "*", After: xlWorkSheet.Cells[1, 1], 
                           SearchOrder: MSOffice.Excel.XlSearchOrder.xlByColumns, 
                           SearchDirection: MSOffice.Excel.XlSearchDirection.xlPrevious);
last.EntireColumn.Delete();

MSOffice.Excel.Range last1 =
    xlWorkSheet.Cells.Find(What: "*", After: xlWorkSheet.Cells[1, 1],
                           SearchOrder: MSOffice.Excel.XlSearchOrder.xlByColumns,
                           SearchDirection: MSOffice.Excel.XlSearchDirection.xlPrevious);
last1.EntireColumn.Delete();

注意:因为较新版本的 C#(自 C# 4.0 起)支持可选参数,所以您不必使用 Missing.Value .


更新:

看起来有一种方法可以重置第一种方法检索到的最后一个单元格的值,那就是调用 Worksheet.UsedRange。因此,如果您愿意,您仍然可以使用您的方法,但每次都必须重新设置值:

MSOffice.Excel.Range last = 
    xlWorkSheet.Cells.SpecialCells(MSOffice.Excel.XlCellType.xlCellTypeLastCell);
last.EntireColumn.Delete();

var dummy = xlWorkSheet.UsedRange;

MSOffice.Excel.Range last1 = 
    xlWorkSheet.Cells.SpecialCells(MSOffice.Excel.XlCellType.xlCellTypeLastCell);
last1.EntireColumn.Delete();