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.
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);
}
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.
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
It works just fine. I guess my question then is what is the equivalent in C#?
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);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With