如何让用户在 c# vsto excel 加载项中选择单元格(范围输入)?



我需要的是让用户控制选择一些将在程序中使用的单元格。该界面在许多 excel 函数中很容易看到,例如在将数据插入图表时。

预先选择的范围可以很容易地作为Globals.ThisAddIn.Application.ActiveWindow.RangeSelection访问,但这不是我要研究的,因为我需要多个这样的范围。 我正在可视化工作室上尝试这个,Interaction.InputBox函数可以获取字符串,据说相当于 vba 的Inputbox,但 vba 的输入框具有输入数据类型的参数,而 c# 输入框没有。

对此的 VBA 等效项是

Dim rngX as Range
Set rngX = Application.InputBox("Select a cell or a range", "Input Cells", Type:=8)

类型:= 8 将使输入框接受范围输入。 但我需要在 C# 中执行此操作(使用 Visual Studio(,并且 C# 的 Inputbox 方法没有像 VBA 那样的输入类型。

Range myRange;
myRange = Globals.ThisAddIn.Application.InputBox("Please select your range?", "Range Selector", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 8);

我尝试了很多,但找不到我想要的确切内容,但此解决方法目前有效。 我使窗体无模式,然后将我需要对范围执行的任何操作放入该窗体中,因此我实际上无法将范围从窗体中发回,但我至少可以执行该任务。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using Microsoft.VisualBasic;
namespace ExcelAddInZeroSofts
{
public partial class InterpolationForm : Form
{
Worksheet ws;
public InterpolationForm(Range rng)
{
InitializeComponent();
tbRange.Text = rng.Address;
}
private void SelectRangeForm_Load(object sender, EventArgs e)
{
ws = Globals.ThisAddIn.Application.ActiveSheet;
ws.SelectionChange += ws_SelectionChange;
// This one will add the event handling to worksheet.
}
void ws_SelectionChange(Range Target)
{
if (this.ActiveControl.Name.First() == 't')
{
this.ActiveControl.Text = Target.Address;
// This one will add the address to the userform (I have 3 fields).
}
}
private void SelectRangeForm_FormClosing(object sender, FormClosingEventArgs e)
{
ws.SelectionChange -= ws_SelectionChange;
}
private void bSubmit_Click(object sender, EventArgs e)
{
// My main Logic Goes here
this.Close();
}
private void bCancel_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

我仍然希望有人能让它像原始的 VBA 输入框一样工作。

最新更新