RemoveDuplicates函数 - 如何设置多列?

时间:2013-07-17 18:13:21

标签: c# excel interop

我正在尝试使用RemoveDuplicates使用Excel.Interop函数,但我仍然坚持如何将列数组传递给它。我已经知道我不能将它作为一个简单的int[]数组传递,因为它在运行时给出了异常,并且我可以传递一个整数并且它可以工作,但是我希望能够选择要使用的列在运行时。

我目前在C#中的代码如下所示:

using Excel = Microsoft.Office.Interop.Excel;

private void removeDuplicates(Excel.Application excelApp, Excel.Range range, int[] columns)
{
    range.RemoveDuplicates(excelApp.Evaluate(columns), 
        Excel.XlYesNoGuess.xlNo); 
}

如果只使用一列,它可以正常工作,但如果columns数组有多个值,则只使用第一列。

在VBA中,等效函数为:

Sub RemoveBadExample()
    Dim colsToUse
    colsToUse = Array(1, 2)
    Selection.RemoveDuplicates Columns:=Evaluate(colsToUse), Header:=xlYes
End Sub

这也无法使用两列。但是,如果我改成它:

    Selection.RemoveDuplicates Columns:=(colsToUse), Header:=xlYes

它运作得很好。我想我的问题是C#中的等价物是什么?

1 个答案:

答案 0 :(得分:5)

这个测试运行对我使用4.5等单位测试。它没有抛出异常。

        Application app = new Application();
        Workbook wb = app.Workbooks.Open("C:\\Data\\ABC.xlsx",
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);
        Worksheet ws = wb.Sheets[1];
        Range rng = ws.Range["A1:C5", Type.Missing];
        object cols = new object[]{1, 2};
        rng.RemoveDuplicates(cols, XlYesNoGuess.xlYes);

请注意,定义范围的Excel单元格索引是基于1而不是零。因此,如果你传递的是一个不好的范围,它将会抛出这种异常。

Object temp = range.Cells[1][1].Value;
相关问题