Code for invoke code activity to merge cells in Excel

I want to merge cells in Excel worksheet using invoke code activity but I m not able to find a suitable code to do the activitiy.



Welcome to uipath forum

If you are looking for invoke code have a view on this thread

But there is a custom activity build on this already which might help you in this scenario

Cheers @Ritesh_Kumar4

1 Like

But I can’t use the custom activity or macro ,that’s why I need a code to run in invoke code


Check below thread for your reference

Hope this will help you


Hi @Ritesh_Kumar4

$xl = New-Object -ComObject Excel.Application -Property @{Visible = $true}
$strPath1=“C:\Users\Admin\Documents\UiPath\test\usecase4.xlsx” // give your excel file path//
$wb = $xl.Workbooks.Open($strPath1)
$sh = $wb.Worksheets.Item(‘Sheet1’)
$mergecells=$sh.Range(‘d2:x2’) // give your excel cell range//
$mergecells.MergeCells = $true

Use the above code in invoke powershell activity


Hi @Ritesh_Kumar4

You can also invoke code using c# as given below. Choose the relevant type of merge for your requirement.

var workbook = new Workbook();
var worksheet = workbook.Worksheets.Add(“AddMerge”);

//Merge entire range
var range = worksheet.Range(“A1:B2”);
range.Value = “Merged A1:B2”;
range.Style.Alignment.Vertical = AlignmentVerticalValues.Top;

//Merge targe row in the range
worksheet.Cell(“A4”).Value = “Merged first row of range(A4:D5)”;
var range2 = worksheet.Range(“A4:D5”);
var rowInRange = range2.Row(1);
rowInRange.Style.Alignment.Horizontal = AlignmentHorizontalValues.Center;

//Merge target column in the range
var range3 = worksheet.Range(“A7:C15”);
var columnInRange = range3.Column(2);
columnInRange.Value = “Merged second column of Range(A7:C10)”;
columnInRange.Style.Alignment.WrapText = true;

//Add border to all ranges
var allMerged = worksheet.Ranges(“A1:B2,A4:D5,A7:C15”).AddToNamed(“MergedRange”);
allMerged.Style.Border.OutsideBorder = BorderStyleValues.Thick;
allMerged.Style.Border.OutsideBorderColor = ExcelColor.Red;


Hope this will be helpful. Thank you.