gpt4 book ai didi

c# - 从功能区按钮访问 Excel 工作表

转载 作者:太空狗 更新时间:2023-10-29 18:11:01 24 4
gpt4 key购买 nike

好的,所以我得到了自动生成的 ma​​in AddIn(附件 1)还有我的功能区(附件 2),我想从该功能区访问当前事件的 Excel 工作表。但是 System.Windows.Forms.Application 不包含 ActiveSheet 的定义。

附件一:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Windows.Forms;

namespace ExcelAddIn1
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{

}

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

#region VSTO 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(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
public void doStuff()
{

}

#endregion



}
}

附件二:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Windows.Forms;

namespace ExcelAddIn1
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{

}

private void button1_Click(object sender, RibbonControlEventArgs e)
{
MessageBox.Show("Test");
Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Application.ActiveSheet);
Excel.Range firstRow = activeWorksheet.get_Range("A1");
firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
Excel.Range newFirstRow = activeWorksheet.get_Range("A1");
newFirstRow.Value2 = "This text was added by using code";
}
}
}

最佳答案

您需要获得 IRibbonControl.Context来自 RibbonControlEventArgs范围。此上下文表示 Excel.Window .然后就可以访问事件Window.Application属性(property)。

private void button1_Click(object sender, RibbonControlEventArgs e)
{
Excel.Window window = e.Control.Context;
MessageBox.Show("Test");
Excel.Worksheet activeWorksheet = ((Excel.Worksheet)window.Application.ActiveSheet);
Excel.Range firstRow = activeWorksheet.get_Range("A1");
firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
Excel.Range newFirstRow = activeWorksheet.get_Range("A1");
newFirstRow.Value2 = "This text was added by using code";
}

关于c# - 从功能区按钮访问 Excel 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com