Rename current sheet, copy current sheet to the same workbook and rename the copied sheet

Does anyone know how to do the following:

  1. Rename current sheet

I tried using hotkey, but sometimes it works but sometimes it doesn’t. Also tried using Invoke VBA but not working.

Tried Invoke Code C# but got this error.

Tried Invoke Code VB.net based on this Renaming an Excel sheet - #3 by aksh1yadav but got compilation error.

  1. Copy current sheet to the same workbook
  2. Rename copied sheet

I use settings Windows (not Windows Legacy) with Classic Experience hence most custom activity cannot be used.

Thank you.

HI,

How about to use ClosedXml as the following?

img20221214-2

using (var varWorkbook = new ClosedXML.Excel.XLWorkbook(workbookPath)){
    var activeSheetname = varWorkbook.Worksheets.First(s=>s.TabActive).Name;
    var srcSheet = varWorkbook.Worksheet(activeSheetname);
        srcSheet.CopyTo(newSheetName);
    varWorkbook.Save();

}

Main.xaml (6.9 KB)

Regards,

Hi @arina

Did you try using copy sheet activity?m

You can copy the same sheet and rename as well

Cheers

Hi @arina
Please use the VB.NET code to achieve your goal.

Declare a variable for the current Excel workbook
Dim workbook As Excel.Workbook

Declare a variable for the current Excel sheet
Dim sheet As Excel.Worksheet

Get the current Excel workbook and sheet
workbook = Excel.ActiveWorkbook
sheet = Excel.ActiveSheet

Rename the current sheet
sheet.Name = “New Sheet Name”

Copy the current sheet to the same workbook
sheet.Copy(After:=workbook.Sheets(workbook.Sheets.Count))

Declare a variable for the new sheet
Dim newSheet As Excel.Worksheet

Get the new sheet that was just added to the workbook
newSheet = workbook.Sheets(workbook.Sheets.Count)

Rename the new sheet
newSheet.Name = “New Sheet Name 2”

Thanks!!!

This method able to complete 2 (Copy current sheet to the same workbook) and 3 (Rename copied sheet) but not 1 (Rename current sheet).

HI,

Can you try yo add srcSheet.Name="newName" as the following?

using (var varWorkbook = new ClosedXML.Excel.XLWorkbook(workbookPath)){
    var activeSheetname = varWorkbook.Worksheets.First(s=>s.TabActive).Name;
    var srcSheet = varWorkbook.Worksheet(activeSheetname);
   srcSheet.CopyTo(newSheetName);
   srcSheet.Name="NewName";
   varWorkbook.Save();
}

Main(4).xaml (6.8 KB)

Regards,

it works !! thank you also somehow adding those lines able to reduce my whole runtime to 40 seconds from 1 minutes 45 seconds

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.