My Blog

Merging/Unmerging Cells

In continuation from here

Here is an example to merge cells A1 to E1.

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1
    '~~> Define your Excel Objects Dim xlApp As New Excel.Application Dim xlWorkBook, xlWorkBook2 As Excel.Workbook Dim xlWorkSheet, xlWsheet2 As Excel.Worksheet Dim xlSourceRange, xlDestRange As Excel.Range Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click '~~> Opens Source Workbook. Change path and filename as applicable
        xlWorkBook = xlApp.Workbooks.Open("C:\Tutorial\Sample.xlsx")

        '~~> Display Excel xlApp.Visible = True '~~> Set the source worksheet
        xlWorkSheet = xlWorkBook.Sheets("Sheet1")

        '~~> Set the source range xlSourceRange = xlWorkSheet.Range("A1", "E1") '~~> Merge the range

        '~~> If you want center alignment of the text horizontly and vertically then use this
        xlSourceRange.HorizontalAlignment = Excel.Constants.xlCenter
        xlSourceRange.VerticalAlignment = Excel.Constants.xlCenter
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    End Sub
End Class