如何将此VBA Excel代码转换为c#

本文关键字:代码 转换 Excel VBA | 更新日期: 2023-09-27 18:04:49

我正在尝试将excel VBA代码转换为c#。这段代码必须在excel之外执行,我要转换我的excel宏这样做。下面是转换

的代码
ActiveWindow.Zoom = 85
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Cells.Select

这是我到目前为止得到的:

var excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = true;
excelApp.ActiveWindow.Zoom = 85;
excelApp.Range["A1"].Select();

我不能算出Range("A1").Select以下的其余部分。有什么帮助吗

如何将此VBA Excel代码转换为c#

with语句只是VB的东西,在c#中你必须创建一个变量,并从该变量显式地调用每个属性

ActiveWindow.Zoom = 85;
Range["A1"].Select();
Range(Selection, Selection.End(xlToRight)).Select();
Selection.HorizontalAlignment = xlCenter;
Selection.VerticalAlignment = xlBottom;
Selection.WrapText = true;
Selection.Orientation = 0;
Selection.AddIndent = false;
Selection.IndentLevel = 0;
Selection.ShrinkToFit = false;
Selection.ReadingOrder = xlContext;
Selection.MergeCells = false;
Cells.Select();

(这只是一个示例,请根据需要调整您的COM处理)

编辑:第二行括号改为方括号

你需要命名空间"Microsoft.Office.Interop.Excel"

using Microsoft.Office.Interop.Excel;
MyClass{
...
    var app = new Application { Visible = true, ScreenUpdating = true, DisplayAlerts = false }; 
    Workbook book = app.Workbooks.Open(path); //path is the fullFileName as string
    Worksheet sheet = book.Worksheets[1];
    Range range = sheet.get_Range("A1", "A1");
    range.Select();
    range.HorizontalAlignment = Constants.xlCenter;
    range.VerticalAlignment = Constants.xlBottom;
    range.WrapText = true;
    range.Orientation = 0;
    range.AddIndent = false;
    range.IndentLevel = 0;
    range.ShrinkToFit = false;
    range.ReadingOrder = Constants.xlContext;
    range.MergeCells = false;
}

享受它!