简体   繁体   English

如何使用 Delete 键删除 Excel 列表对象列?

[英]How to delete an Excel listobject column with the Delete key?

When the active cell in an Excel listobject is a column header, I would like to programmatically (in C#) handle pressing the DEL key as the equivalent to deleting that column.当 Excel 列表对象中的活动单元格是列标题时,我想以编程方式(在 C# 中)处理按下 DEL 键,相当于删除该列。 Currently, if I press the DEL key, the header name will change into a default name automatically generated by Excel (eg List1, or Spalte1 in my case of a German version of Excel).目前,如果我按 DEL 键,标题名称将更改为 Excel 自动生成的默认名称(例如 List1,或在我的德国版 Excel 中的 Spalte1)。

Trapping a keypress event for the DEL key is an option I would like to avoid, as I don't want to stress unnecessarily the application by permanently having to monitor for any kind of keypress events.为 DEL 键捕获按键事件是我想避免的一个选项,因为我不想通过永久监视任何类型的按键事件来给应用程序带来不必要的压力。

Therefore, I am wondering if there is any way to determine what the default naming of the column header will be after pressing the Delete key, so that I can implement a Change event handler which will compare the new header content with that default name, and thus interpret this as a column delete action (of course asking the user for confirmation!).因此,我想知道是否有任何方法可以确定按下 Delete 键后列标题的默认命名是什么,以便我可以实现一个 Change 事件处理程序,它将新标题内容与该默认名称进行比较,并且因此将其解释为列删除操作(当然要求用户确认!)。

In the change event handler, the code could look like this (here, it is assumed that ActiveCell is the header column name of the column that is to be removed):在更改事件处理程序中,代码可能如下所示(这里假设 ActiveCell 是要删除的列的标题列名称):

string headerName = ActiveCell.Value2;
int colIdx = ActiveCell.Column - myListObject.Range.Column +1;
Excel.ListColumn columnToDelete = myListObject.ListColumns[colIdx];
if (headerName == someDefaultName)
{
    columnToDelete.Delete();
}

Is there anyway how I can determine someDefaultName without having to compare with a list of default names for all possible languages supported by Excel??无论如何,我如何确定 someDefaultName 而不必与 Excel 支持的所有可能语言的默认名称列表进行比较?

Below is my idea.下面是我的想法。 It is based on following worksheet:它基于以下工作表:
在此处输入图片说明

with the ListObject "list1".与列表对象“list1”。 It contains 5 columns.它包含 5 列。 The main idea - is to add a new column on the startup, catch it's header, remove numbers from this text and put it into a variable to compare changes sent by ListObject_Change event.主要思想 - 是在启动时添加一个新列,捕获它的标题,从该文本中删除数字并将其放入一个变量中以比较 ListObject_Change 事件发送的更改。 As soon as someone presses Del on the header row - it will be changed to default name and deleted.只要有人在标题行上按下 Del - 它就会更改为默认名称并删除。 Nevertheless, it would not delete a new column with default name.尽管如此,它不会删除具有默认名称的新列。

public partial class Sheet1
{
    // assign temp variables for header range and a column name
    // template
    public Excel.Range HeaderRange { get; set; }
    public string template;


    private void Sheet1_Startup(object sender, System.EventArgs e)
    {
        // subscribe to ListObject change event
        list1.Change += new Microsoft.Office.Tools.Excel.ListObjectChangeHandler(list1_Change);
        // get the template on start (switch of events for a while)
        this.Application.EnableEvents = false;
        GetDefaultColumnHeaderTemplate();
        this.Application.EnableEvents = true;
    }

    private void Sheet1_Shutdown(object sender, System.EventArgs e)
    {
    }


    //ListObject change event:
    void list1_Change(Microsoft.Office.Interop.Excel.Range targetRange, Microsoft.Office.Tools.Excel.ListRanges changedRanges)
    {
        // assign variables to simplify the code below
        Excel.Range Intersection = Globals.Sheet1.Application.Intersect((Excel.Range)targetRange, HeaderRange);
        HeaderRange = list1.HeaderRowRange;

        // if range is assigned - means that change was done in header row
        if (!(Intersection == null))
        {
            // make sure that changed range is only one cell
            if (Intersection.Rows.Count < 2 && Intersection.Columns.Count < 2)
            {
                // if this cell contains template - delete entire column 
                if ((targetRange.Value2).ToString().Contains(template))
                {
                    targetRange.EntireColumn.Delete();
                }
            }
        }
    }

    private void GetDefaultColumnHeaderTemplate()
    {
        // add a column with default name
        Excel.ListColumn tempColumn = list1.ListColumns.Add();

        // re-assign headers range
        HeaderRange = list1.HeaderRowRange;

        // catch the name of new column with default name
        // and remove a number  counter
        template = GetTextTemplate(HeaderRange.Cells[1, HeaderRange.Columns.Count].Value2.ToString());

        // delete temp column
        tempColumn.Delete();
    }

    private string GetTextTemplate(string tx)
    {
        string tmp = null;

        // go through each char of default column name and take only letters
        for (int i = 0; i < tx.Length; i++)
        {
            if (!double.TryParse(tx.Substring(i, 1), out _))
            {
                tmp += tx.Substring(i, 1);
            }
        }
        return tmp;
    }
        #region VSTO Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(this.Sheet1_Startup);
        this.Shutdown += new System.EventHandler(this.Sheet1_Shutdown);

    }

    #endregion

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM