c# - RemoveDuplicates 函数 - 如何设置多列?

标签 c# excel interop

我正在尝试通过 Excel.Interop 使用 RemoveDuplicates 函数,但我不知道如何将列数组传递给它。我已经知道我不能将它作为一个简单的 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# 中的等效项是什么?

最佳答案

这个测试运行在使用 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;

关于c# - RemoveDuplicates 函数 - 如何设置多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17707182/

相关文章:

c# - 如何将C#中的日期字符串变量与sql查询中的日期时间字段进行比较

java - 在 Java 中使用 RSA 公钥加密数据并在 Crypto++ 中解密

c# - 如何使任务栏在失去焦点时闪烁

excel - 忽略具有多个自变量的 Excel LINEST 函数中的零(或空白)

vba - 剪切粘贴某行数据

python - 来自 csv 的 Pandas Dataframe 显示不正确

delphi - 在 Delphi 中,在 Excel Interop Worksheets 集合上使用 for 循环时,如何处理 "no GetEnumerator present"错误?

c# - 如何从 CultureInfo 中的属性获取时区

c# - 通过经典 ASP 的 COM Interop(如何将数组传递给 com)

c# - 正则表达式使用变量用于相同的字符串模式属性 C#