Say you have an
Excel.Range
variable called, e.g.,
MergeRange
that represents the range of cells you would've otherwise highlighted had you been working directly with an open instance of Excel.
Now suppose we want to Merge and Center the text that is in the range. How do we do this? By the below:
public void MergeAndCenter(Excel.Range MergeRange) {
MergeRange.Select();
MergeRange.HorizontalAlignment = XlHAlign.xlHAlignCenter;
MergeRange.VerticalAlignment = XlVAlign.xlVAlignBottom;
MergeRange.WrapText = false;
MergeRange.Orientation = 0;
MergeRange.AddIndent = false;
MergeRange.IndentLevel = 0;
MergeRange.ShrinkToFit = false;
MergeRange.ReadingOrder = (int)(Constants.xlContext);
MergeRange.MergeCells = false;
MergeRange.Merge(System.Type.Missing);
}
Ta-da! Works with the Microsoft Excel v12.0 and above object libraries.
You know how I did this? I opened up an instance of Excel on my own, typed in some text and performed a merge and center -- all while recording a Macro.
Then I just did a 'View Code' (on the Developer tab -- you can show it using the Ribbon Orb > Excel Options and then somewhere there's a check box that says "Show the Developer toolbar" -- and there's also Record Macro/Stop Macro buttons there) and then opened up the VBA module corresponding to the Macro.
I then translated the VBA code to C# equivalents.
Bonus tip: Now you don't have to Google search for how to do something with Excel Interop -- just record a macro, do it by hand, stop the macro, view its code, translate to your interop language and voila!
Brian C. Hart, Ph.D., is a strategic engagement leader on a mission to leverage space technology to protect U.S. interests and assets against adversaries. Throughout Dr. Hart's career, he has enjoyed: Working closely with business executives to provide strategic direction and leadership, translating customer and competitive intelligence into compelling capture strategies and solutions, and mentoring teams to enhance individual and company capabilities while fostering an engaging and accountable environment, being involved in STEAM initiatives and education to develop greater awareness in the community, and serving the armed forces with the U.S. Navy and U.S. Army National Guard. He is excited to begin developing his career in Jacobs's Critical Mission Systems business unit, supporting NORAD and the U.S. Space Force.