1

I am trying to convert excel VBA code to c#. This code must be executed outside excel and I am going to convert my excel macros to do so. Here is the code to convert

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

Here is what I got so far:

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

I cannot figure out the rest below the Range("A1").Select. Any help on this

1
  • 1
    C# doesn't support with, so just do Selection.HorizontalAlign = xlCenter;, Selection.VerticalAlignment = xlBottom;, etc. Commented Mar 19, 2013 at 20:26

2 Answers 2

2

The with statement is a VB thing only, with c# you have to create a variable and call each of the properties from that variable explicitly

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();

(this is just a sample, do adjust your COM handling as required)

EDIT: Changed brackets to square brackets one the second line.

Sign up to request clarification or add additional context in comments.

1 Comment

You're forgetting to use brackets - Range["A1"]...
0

You need the namespace "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;
}

Enjoy it!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.