Translate Copy / Paste in excel from VBA code to C# - c#

I have this vba code that i am trying to convert into C# using Microsoft.Office.Interop.Excel.
So the code is :
Columns("AN:AS").Select
Selection.Copy
Columns("AT:AT").Select
Selection.Insert Shift:=xlToRight
Columns("AT:AY").Select
Selection.Replace What:="ST", Replacement:="TO", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Application.CutCopyMode = False
I have look into some solutions but i am keep getting errors.
This is what i have done :
Range source = (Microsoft.Office.Interop.Excel.Range)currentSheet.get_Range("AN:AS").Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight);
Range destination = currentSheet.get_Range("AT: AT");
source.Copy(destination);
currentSheet.get_Range("AT:AY").Replace("ST", "TO", SearchOrder : 1 , LookAt : 2, MatchCase: false, SearchFormat: false, ReplaceFormat: false);
currentSheet.Application.CutCopyMode = 0;
And i got error at the source variable saying :
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: Impossible de convertir le type 'bool' en 'Microsoft.Office.Interop.Excel.Range'
My goal is to transform that code from VBA to C#.

My goal is to transform that code from VBA to C#.
that should does the job:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Range source = currentSheet.get_Range("AN:AS");
Excel.Range destination = currentSheet.get_Range("AT:AT");
destination.Insert(XlInsertShiftDirection.xlShiftToRight, source.Copy());
currentSheet.get_Range("AT:AY").Replace("ST", "TO", SearchOrder: 1, LookAt: 2, MatchCase: false, SearchFormat: false, ReplaceFormat: false);
// avoid to have a message about clipboard before saving the file
currentSheet.Application.CutCopyMode = XlCutCopyMode.xlCopy;

Thank you for all the response.
This is what work finally for me.
Range source = currentSheet.get_Range("AN:AS");
source.Select();
source.Copy();
Range destination = (Microsoft.Office.Interop.Excel.Range)currentSheet.get_Range("AT:AT");
destination.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight);
Range range_sheet = currentSheet.get_Range("AT:AY");
range_sheet.Select();
range_sheet.Replace("ST", "TO", SearchOrder: XlSearchOrder.xlByRows, LookAt: XlLookAt.xlPart, MatchCase: false, SearchFormat: false, ReplaceFormat: false);
currentSheet.Application.CutCopyMode = 0;

Related

Cannot set Data Validation in Excel by using MATCH formula C#

After use MATCH formula to validationStr, my class went wrong.
Can anyone tell me why error happened?
ERROR:
System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800A03EC'
Thank you very much!
using Microsoft.Office.Interop.Excel;
string validationListStr = "=OFFSET($AB$12,1,MATCH($T$12,$AB$12:$AD$12,0)-1,COUNTA(OFFSET($AB$12,1,MATCH($T$12,$AB$12:$AD$12,0)-1,100,1)),1)";
workSheet.Cells[1, 1].Validation.Delete();
workSheet.Cells[1, 1].Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertInformation, Type.Missing, validationListStr, Type.Missing);
workSheet.Cells[1, 1].Validation.IgnoreBlank = true;
workSheet.Cells[1, 1].Validation.InCellDropdown = true;
I set the formula to validation by hand in Excel. There was no problem.
However, I cannot set the formula by C#.
The wrong 'Missing' object is being passed to the Add function.
System.Type.Missing needs to be changed to System.Reflection.Missing.Value
workSheet.Cells[1, 1].Validation.Add(
XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertInformation,
Missing.Value, // <-
validationListStr,
Missing.Value // <-
);

Excel Vlookup with C#

I am trying to use WorksheetFunction.VLookup but I get the message:
"VLookup method of WorksheetFunction class failed"
my code:
Excel.Range xlRange = (Excel.Range)xlWorksheet.get_Range("3:1", "333:20");
label4.Text = xlApp.WorksheetFunction.VLookup("MAF0510530146", xlRange, 7, false);
do you have any idea what went wrong?
the input string "MAF0510530146" is in the excel file...
Thanks

Range Validator in Excel with custom message text

I have the following code to give a Excel cell Validation with custom text.
var cellValues = activeSheet.Range[columnLetterValue + startingRow, Type.Missing];
cellValues.Validation.Add(XlDVType.xlValidateCustom, XlDVAlertStyle.xlValidAlertInformation, XlFormatConditionOperator.xlBetween, cellValues.Value2, Type.Missing);
cellValues.Validation.IgnoreBlank = true;
cellValues.Validation.ErrorTitle = "Custom error title";
cellValues.Validation.ErrorMessage = "Custom error message description";
cellValues.Validation.ShowError = true;
cellValues.Validation.ShowInput = false;
When debugging the line to set the ErrorTitle or ErrorMessage a 'System.Runtime.InteropServices.COMException' is thrown.
Stacktrace:
{System.Runtime.InteropServices.COMException (0x800A03EC): Exception
from HRESULT: 0x800A03EC at
System.RuntimeType.ForwardCallToInvokeMember(String memberName,
BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData&
msgData) at
Microsoft.Office.Interop.Excel.Validation.set_ErrorTitle(String )
I have looked online and found a couple of examples that show this is possible:
Range Validation with Excel using C#
I've even recorded a Macro in Excel and it works with the "VBA" equivilent code:
ActiveCell.FormulaR1C1 = "Custom"
Range("A1").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertInformation, _
Operator:=xlBetween, Formula1:="Custom"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = "UDF Title"
.InputMessage = ""
.ErrorMessage = "The message"
.ShowInput = False
.ShowError = True
End With
End Sub
I've also tried different combinations of XlDVType and XlFormatConditionOperator but that didn't seem to make any difference in setting the custom messagebox text.
Does anyone know how to set a Validation rule with custom ErrorTitle and ErrorMessage?
The problem was due to setting a Validation.ErrorTitle to a range that didn't have a Validation rule.

how to cast COM object type to Excel.Checkbox type

I am adding a checkbox to excel and i have issue casting a COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.CheckBox', any help would be appreciated! I am working on web app using visual studio 2008 and office 2007. The error happens at this line :- chkBx = (Microsoft.Office.Interop.Excel.CheckBox)obj;
Microsoft.Office.Interop.Excel.OLEObjects objs = (Microsoft.Office.Interop.Excel.OLEObjects)mWSheet1.OLEObjects(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.OLEObject obj = objs.Add("Forms.CheckBox.1",
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
false,
false,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
234,
234,
108,
21);
Microsoft.Office.Interop.Excel.CheckBox chkBx;
chkBx = (Microsoft.Office.Interop.Excel.CheckBox)obj;
chkBx.Value = true;
chkBx.Caption = "xyz";
It looks to me like you can't cast it because it simply doesn't implement that interface. You can check if a System.__ComObject supports an interface without casting, and consequently throwing an exception, by using the as operator as described here: HOW TO: Check the Type of a COM Object (System.__ComObject) with Visual C# .NET.
I wonder if you are using the wrong method to add the checkbox to a worksheet. Isn't the more common method to go through Microsoft.Office.Tools.Excel.ControlCollection as described here: Adding Controls to Office Documents at Run Time.
If you used ControlCollection, I think your code would end up looking something like this:
private void AddCheckBox()
{
Worksheet vstoWorksheet = Globals.Factory.GetVstoObject(
this.Application.ActiveWorkbook.Worksheets[1]);
System.Windows.Forms.CheckBox checkbox =
new System.Windows.Forms.CheckBox();
checkbox.Checked = true;
checkbox.Text = "xyz"
vstoWorksheet.Controls.AddControl(234, 234, 108, 21, "checkbox1");
}

Excel.PivotField.DataRange.Cells.Group does not work. Why?

The following code won't build.
var Date = (Excel.PivotField)pivotTable.PivotFields("Date");
Date.Orientation = Excel.XlPivotFieldOrientation.xlColumnField;
Date.Position = 1;
Date.DataRange.Cells[1].Group(true, true, Type.Missing, GroupParam);
Group is marked as causing an error. The error message is 'object' does not contain a definition for 'Group' and no extension method 'Group' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
How can I fix this error?
I am using VS 2012 together with VSTO and add-in express
You should probably declare intermediate variables if you are experiencing compile issues. It fairly apparent from testing that the Group method exists and should be accessible by your code. Give the compiler some help and declare the variable:
The extreme version of this philosophy worked fine for me using Group:
private void button2_Click(object sender, EventArgs e)
{
Excel.Worksheet sht = app.ActiveSheet;
Excel.PivotTable pt = sht.PivotTables(1);
Excel.PivotField pf = pt.PivotFields("DATE");
Excel.Range rng = pf.DataRange;
Excel.Range cell = rng.Cells[1];
cell.Group(true, true, Type.Missing, new bool[] { false, false, false, false, true, true, false });
}
Excel.Range rng = pf.DataRange;
Excel.Range cell = rng.Cells[1];
cell.Group(true, true, Type.Missing, new bool[] { false, false, false, true, false, true, true });
As mentioned above, There are number of parameter passed as true and false in bool array. The value is set to true or false depending on filter you want like for month, year etc.
See image. The parameter order is same as the passed value

Categories