Cut and paste columns in Excel using C #

I am trying to move column B in front of column Q in an excel sheet as part of the report I'm working on. I have experience in VBA, but relatively little in C #, so I spent the last hour at Google and can’t find a solution, I feel that it should be simple, but I can’t get it.

First method, as a result of which the "Insert method of the Range class did not work" msg.

Excel.Range rngCut1 = JobLabourSheet.get_Range("B:B", Type.Missing);
Excel.Range rngPaste1 = JobLabourSheet.get_Range("Q:Q", Type.Missing);
            rngCut1.Columns.Cut(rngPaste1.EntireColumn.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, rngCut1));

The two method results in "Unable to get Cut property for Range class" msg.

Excel.Range rngCut1 = JobLabourSheet.get_Range("B:B", Type.Missing);
Excel.Range rngPaste1 = JobLabourSheet.get_Range("Q:Q", Type.Missing);
            rngCut1.Columns.Cut(rngPaste1.EntireColumn.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, Missing.Value));

In the second method, when I omit CopyOrigin, I get msg, but it inserts an empty column before Q column.

In VBA, I would use the following:

Columns("B:B").Cut
Columns("Q:Q").Insert Shift:=xlToRight

But, as I said, my experience with C # is currently limited, so I have no idea how to translate it to C #

+4
1

, . "" Insert() "range.Cut()" " ".

:

( Microsoft.Office.Interop.Excel):

using System;
using System.Collections.Generic;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelCutAndInsertColumn
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWb = xlApp.Workbooks.Open(@"C:\stackoverflow.xlsx");
            Excel.Worksheet xlWs = (Excel.Worksheet)xlWb.Sheets[1]; // Sheet1

            xlApp.Visible = true;

            // cut column B and insert into A, shifting columns right
            Excel.Range copyRange = xlWs.Range["B:B"];
            Excel.Range insertRange = xlWs.Range["A:A"];

            insertRange.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, copyRange.Cut());
        }
    }
}
+3

All Articles