我正在尝试通过 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/