我在Google和此处都进行了搜索,但找不到解决方案/原因。
我正在Visual Studio 2019中使用Excel加载项,该加载项在ListView中列出了当前工作簿中的工作表。我还向窗口添加了2个按钮,一个标记为“上移”,另一个标记为“下移”。单击这些按钮后,应该将ListView.SelectedItem移至当前位置之前或之后。
这没有发生,相反,我收到了System.Runtime.InteropServices.COMException (HRESULT=0x800A03EC), "Cannot evaluate the exception source"
。我不知道是什么原因造成的,根据Microsoft Docs,我使用的代码是正确的。有人可以看一下代码,看看他们是否发现我做错了什么?
代码
(在找到Microsoft Doc代码之前,ChangeSheetOrder函数中注释掉的代码是我的最初方法。)
WorksheetsListBox
是ListView
public partial class DocumentWorksheets : Form
{
List<Worksheet> sheets = new List<Worksheet>();
List<string> sheetNames = new List<string>();
Excel.Workbook currentWorkbook = Globals.ThisWorkbook.Application.ActiveWorkbook as Excel.Workbook;
public DocumentWorksheets()
{
InitializeComponent();
CatalogWorksheets();
}
public void CatalogWorksheets()
{
sheets.Clear();
int numSheets = currentWorkbook.Sheets.Count;
for (int i = 1; i < numSheets; i++)
{
sheets.Add((Excel.Worksheet)currentWorkbook.Sheets[i]);
}
foreach (Worksheet sheet in sheets)
{
sheetNames.Add(sheet.Name);
}
WorksheetsListBox.DataSource = sheetNames;
IsDirty();
}
public void IsDirty()
{
WorksheetsListBox.Refresh();
}
private void MoveUpButton_Click(object sender, EventArgs e)
{
ChangeSheetOrder(true);
IsDirty();
}
private void MoveDownButton_Click(object sender, EventArgs e)
{
ChangeSheetOrder(false);
IsDirty();
}
public void ChangeSheetOrder(bool directionIsUp)
{
Worksheet selected = Globals.ThisWorkbook.Worksheets[WorksheetsListBox.SelectedIndex];
int currentIndex = selected.Index + 1;
if (directionIsUp)
{
((Excel.Worksheet)currentWorkbook.ActiveSheet).Move(currentIndex + 1);
//selected.Move(Before: Globals.ThisWorkbook.Worksheets[WorksheetsListBox.SelectedIndex]);
}
else
{
((Excel.Worksheet)currentWorkbook.ActiveSheet).Move(currentIndex - 1);
//selected.Move(After: Globals.ThisWorkbook.Worksheets[WorksheetsListBox.SelectedIndex]);
}
CatalogWorksheets();
}
private void WorksheetsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedItem = WorksheetsListBox.SelectedIndex + 1;
//Added to prevent firing before Window fully loaded and ListView Collection created
if (this.IsHandleCreated)
{
((Excel.Worksheet)currentWorkbook.Sheets[selectedItem]).Select();
}
IsDirty();
}
private void WorksheetsListBox_Layout(object sender, LayoutEventArgs e)
{
MessageBox.Show("Redrawn");
}
}