首页 > 解决方案 > 将 Excel 中的复制/粘贴从 VBA 代码转换为 C#

问题描述

我有这个 vba 代码,我正在尝试使用 Microsoft.Office.Interop.Excel 将其转换为 C#。

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

我已经研究了一些解决方案,但我不断收到错误。

这就是我所做的:

      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'

我的目标是将代码从 VBA 转换为 C#。

标签: c#excelvbaexcel-interop

解决方案


我的目标是将代码从 VBA 转换为 C#。

那应该做的工作:

        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;

推荐阅读