RemoveDuplicates函数-如何设置多列? [英] RemoveDuplicates function - how can I set multiple columns?

查看:169
本文介绍了RemoveDuplicates函数-如何设置多列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Excel.Interop来使用RemoveDuplicates函数,但是我对如何将其传递给列数组感到困惑.我已经知道我不能将其作为简单的int[]数组传递,因为它在运行时会产生异常,并且我可以传递单个整数并且它可以工作,但是我希望能够选择在运行时使用哪些列

I'm trying to use the RemoveDuplicates function using Excel.Interop, but I'm stuck as to how to pass it the column array. I already know that I cannot pass it as a simple int[] array, as it gives an exception at runtime, and that I can pass a single integer and it works, but I want to be able to select which columns to use at runtime.

我当前在C#中的代码如下:

My current code in C# looks like this:

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数组具有多个值,则仅使用第一个值.

And it works fine if using only one column, but if the columns array has more than one value, only the first one is used.

在VBA中,等效功能为:

In VBA, the equivalent function would be:

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

哪个也不能同时使用两个列.但是,如果我将其更改为此:

Which also fails to use both columns. however, if I change it to this:

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

效果很好.我想我的问题是C#的等效功能是什么?

It works just fine. I guess my question then is what is the equivalent in C#?

推荐答案

在使用4.5等的单元测试中,此测试运行对我有用.它丝毫没有引发异常.

This test run worked for me in a unit test using 4.5 etc. It did not throw an exception at any rate.

        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,而不是零.因此,如果您传递的范围不正确,则会引发此类异常.

Be aware that excel cell indices that define ranges are 1 based, not zero. So if you are passing in a bad range it will throw that kind of exception.

Object temp = range.Cells[1][1].Value;

这篇关于RemoveDuplicates函数-如何设置多列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆