|
本帖最后由 394286425 于 2017-6-21 21:39 编辑
- private void ThisAddIn_Startup(object sender, System.EventArgs e)
- {
- AddContextMenuStrip();
- }
- private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
- {
- }
- private void AddContextMenuStrip()
- {
- CommandBar mzBar = Globals.ThisAddIn.Application.CommandBars["cell"]; //excel文档已有的右键菜单cell
- if (mzBar == null) { return; }
- foreach (CommandBarControl temp_contrl in mzBar.Controls)
- {
- temp_contrl.Delete(false);
- }
- //长度自动合并
- CommandBarButton btnAutoMerge = (CommandBarButton)mzBar.Controls.Add(MsoControlType.msoControlButton, missing, missing, missing, true);
- btnAutoMerge.Tag = "btn_AutoMerge";
- btnAutoMerge.Caption = "长度自动合并";
- btnAutoMerge.Style = MsoButtonStyle.msoButtonIconAndCaption;
- btnAutoMerge.FaceId = 3277;
- btnAutoMerge.Click += new _CommandBarButtonEvents_ClickEventHandler(btnAutoMerge_Click);
- }
- //长度自动合并
- private void btnAutoMerge_Click(CommandBarButton Ctrl, ref bool CancelDefault)
- {
-
- MessageBox.Show("长度自动合并");
- LengthAutoMerge();
-
- }
- //长度自动合并
- public void LengthAutoMerge()
- {
- Excel.Application xls = Globals.ThisAddIn.Application;
- xls.ScreenUpdating = false;
- Excel.Workbook wb = xls.ActiveWorkbook;
- Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
- Range rng = (Range)xls.ActiveWindow.Selection;
- int topRow = rng.Row;
- int endRow = rng.Row + rng.Rows.Count - 1;
- int leftCol = rng.Column;
- int rightCol = rng.Column + rng.Columns.Count - 1;
- Dictionary<int, int> dict = new Dictionary<int, int>();
- List<int[]> lsList = new List<int[]>() { };
- for (int i = topRow; i <= endRow; i++)
- {
- Range rngLenth = (Range)ws.Cells[i, leftCol];
- int length = Convert.ToInt32(rngLenth.Text);
- Range rngNum = (Range)ws.Cells[i, rightCol];
- int num = Convert.ToInt32(rngNum.Text);
- if (dict.ContainsKey(length))//长度已有则数量相加
- {
- dict[length] = dict[length] + num;
- }
- else//没有则添加
- {
- dict.Add(length, num);
- }
- }
- var dicSort = from objDic in dict orderby objDic.Key descending select objDic;
- foreach (KeyValuePair<int, int> kvp in dicSort)
- {
- lsList.Add(new int[] { kvp.Key, kvp.Value });
- }
- for (int j = 0; j < lsList.Count; j++)
- {
- ((Range)ws.Cells[topRow + j, 16]).Value = lsList[j][1];
- ((Range)ws.Cells[topRow + j, 17]).Value = lsList[j][0];
- }
- xls.ScreenUpdating = true;
- }
复制代码 ·自定义的右键菜单点击一次后能运行,继续点击就没反应了。求解救!
|
|