Range in .Select() not working on xlApp.ActiveWindow.FreezePanes - vb.net

I just want to select A1 to A3 to freeze pane. But xlApp.ActiveWindow.FreezePanes freezes A1 to A10. I was experimenting for 3 hours is this line of code for 3 hours:
xlApp.Range("A1:A3").Select()
But still A1 to A10 are the cells that are freeze. I just want to freeze A1 to A3. Is this possible? Im using Visual Studio 2012 and Excel 2013
Here is my code:
Imports System.Data.OleDb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'AccessdbtestDataSet.country' table. You can move, or remove it, as needed.
Me.CountryTableAdapter.Fill(Me.AccessdbtestDataSet.country)
Dim con As New OleDbConnection
Dim query As String = "SELECT * FROM country"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=accessdbtest.accdb"
con.Open()
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter(query, con)
da.Fill(dt)
DataGridView1.DataSource = ds.Tables(0)
con.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
Dim xlCenter As String = "center"
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
//Merging cells
xlWorkSheet.Range("A1:D1").MergeCells = True
xlWorkSheet.Range("A2:D2").MergeCells = True
xlWorkSheet.Range("A3:D3").MergeCells = True
//Assigning text to the merge cells
xlWorkSheet.Cells(1, 1) = "Republic of the Philippines"
xlWorkSheet.Cells(2, 1) = "NCR"
xlWorkSheet.Cells(3, 1) = "Manila"
//Put the text in the center of the merge cells
xlWorkSheet.Range("A1:A1").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
xlWorkSheet.Range("A2:A2").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
xlWorkSheet.Range("A3:A3").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
For i = 5 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i - 3).Value.ToString()
Next
Next
//This line of code is not working <-------------------------<|
xlApp.Range("A1:A3").Select()
xlApp.ActiveWindow.FreezePanes = True
xlWorkSheet.SaveAs("C:\excel\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file C:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

xlApp.Range("A4").Select
Then apply the freeze panes.

Related

Datagridview Horizontal to vertical button

The following code isn't working when exporting the datagridview data when trying to make it vertical with headers along the left side along with text beside each one. Once this is flipped the user would click on button1 to export to excel.
Imports System.Data.DataTable
Imports System.IO
Imports Microsoft.Office.Interop
Public Class Form1
Dim table As New DataTable(0)
Public checkBoxList As List(Of CheckBox)
Private ds As DataSet = Nothing
Private dt As DataTable = Nothing
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ds = New DataSet()
dt = New DataTable()
ds.Tables.Add("Table")
Dim my_DataView As DataView = ds.Tables(0).DefaultView
DataGridView1.DataSource = my_DataView
table.Columns.Add("Forename", Type.GetType("System.String"))
table.Columns.Add("Surname", Type.GetType("System.String"))
table.Columns.Add("Food", Type.GetType("System.String"))
checkBoxList = New List(Of CheckBox) From {CheckBox1, CheckBox2, CheckBox3, CheckBox4}
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim currentDataSet As DataSet = FlipDataSet(ds) ' Flip the DataSet
Dim values As String = "" &
String.Join(" & ", checkBoxList _
.Where(Function(cb) cb.Checked).Select(Function(cb) cb.Text))
' use values for placing into your DataGridView
CheckBox1.Text = values
CheckBox2.Text = values
CheckBox3.Text = values
CheckBox4.Text = values
table.Rows.Add(TextBox1.Text, TextBox2.Text, values.ToString)
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DataGridView1.RowTemplate.Height = 100
DataGridView1.AllowUserToAddRows = False
DataGridView1.DataSource = table
'Save to excel with headers
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
'create object of excel
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
For Each column As DataGridViewColumn In DataGridView1.Columns
.cells(1, column.Index + 1) = column.HeaderText
Next
For i = 1 To Me.DataGridView1.RowCount
.cells(i + 1, 1) = Me.DataGridView1.Rows(i - 1).Cells("Forename").Value
For j = 1 To DataGridView1.Columns.Count - 1
.cells(i + 1, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
Next
Next
End With
ExcelApp.Visible = True
'
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Public Function FlipDataSet(ByVal my_DataSet As DataSet) As DataSet
Dim ds As New DataSet()
For Each dt As DataTable In my_DataSet.Tables
Dim table As New DataTable()
For i As Integer = 0 To dt.Rows.Count
table.Columns.Add(Convert.ToString(i))
Next
Dim r As DataRow
For k As Integer = 0 To dt.Columns.Count - 1
r = table.NewRow()
r(0) = dt.Columns(k).ToString()
For j As Integer = 1 To dt.Rows.Count
r(j) = dt.Rows(j - 1)(k)
Next
table.Rows.Add(r)
Next
ds.Tables.Add(table)
Next
Return ds
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim currentDataSet As DataSet = FlipDataSet(ds) ' Flip the DataSet
Dim currentDataView As DataView = currentDataSet.Tables(0).DefaultView
DataGridView1.DataSource = currentDataView
Button2.Enabled = False
End Sub
End Class
When clicking button2 it should flip the data with the following;
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles
Button2.Click
Dim currentDataSet As DataSet = FlipDataSet(ds) ' Flip the DataSet
Dim currentDataView As DataView = currentDataSet.Tables(0).DefaultView
DataGridView1.DataSource = currentDataView
Button2.Enabled = False
End Sub
End Class
I've tried debugging but it i can't seem to find anything wrong? It will allow me to insert data in the textbox's whilst selecting checkbox's and when clicking button 1 to export it works fine, but it doesn't flip the data.
Please can anyone suggest how to fix this as i have a presentation on the 8th June and this data needs to automatically be flipped
Sourcecode: Download Myproject
Image of target
Answered:
Imports Microsoft.Office.Interop
Imports System.Runtime.InteropServices
Public Class Form1
Private ds As DataSet = Nothing
Private dt As DataTable = Nothing
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AllowUserToAddRows = False
dt = New DataTable("MyTable")
dt.Columns.Add("Forename", Type.GetType("System.String"))
dt.Columns.Add("Surname", Type.GetType("System.String"))
dt.Columns.Add("Food", Type.GetType("System.String"))
ds = New DataSet
ds.Tables.Add(dt)
Dim my_DataView As DataView = ds.Tables("MyTable").DefaultView
DataGridView1.DataSource = my_DataView
End Sub
Private Sub Button_AddRowData_Click(sender As Object, e As EventArgs) Handles Button_AddRowData.Click
Dim foods As String = String.Join(" & ", CheckedListBox1.CheckedItems.Cast(Of String))
dt.Rows.Add(New Object() {TextBox_Forename.Text, TextBox_Surname.Text, foods})
End Sub
Private Sub Button_FlipAndSave_Click(sender As Object, e As EventArgs) Handles Button_FlipAndSave.Click
FlipAndSave(ds.Tables("MyTable"))
End Sub
Private Sub FlipAndSave(table As DataTable)
Dim ExcelApp As New Excel.Application
Dim WrkBk As Excel.Workbook = ExcelApp.Workbooks.Add()
Dim WrkSht As Excel.Worksheet = CType(WrkBk.Worksheets(1), Excel.Worksheet)
With WrkSht
For ci As Integer = 0 To table.Columns.Count - 1
.Cells(ci + 1, 1) = table.Columns(ci).ColumnName
Next
For ri As Integer = 0 To table.Rows.Count - 1
For ci As Integer = 0 To table.Columns.Count - 1
.Cells(ci + 1, ri + 2) = table.Rows(ri).Item(ci).ToString
Next
Next
End With
ExcelApp.Visible = True
'use this lines if you want to automatically save the WorkBook
'WrkBk.SaveAs("C:\Some Folder\My Workbook.xlsx") '(.xls) if you have an old version of Excel
'ExcelApp.Quit() 'use this line if you want to close the Excel Application
ReleaseObject(ExcelApp)
ReleaseObject(WrkBk)
ReleaseObject(WrkSht)
End Sub
Private Sub ReleaseObject(obj As Object)
Marshal.ReleaseComObject(obj)
obj = Nothing
End Sub
End Class

DataGridView To Excel With Colored Cells in vb.net

I looked a lots of example and demo but I could not to it.
I'm trying to convert datagridview to excel with background color .
i can only datagridview to excel but without background color. i want export excel with background color .
this my code .
Imports System.Data.SqlClient
Imports System.Data.OleDb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class view_all
Dim con1 As SqlConnection 'cun concation
Dim con As String ' string coonction
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim APP As New Excel.Application
Dim worksheet As Excel.Worksheet
Dim workbook As Excel.Workbook
Dim view As DataView
Private Sub view_all_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim obj As New config
con1 = New SqlConnection
con1 = obj.getcontion()
con1.Open()
MessageBox.Show("Open Stock Limit ", "Open", MessageBoxButtons.OK, MessageBoxIcon.Information)
da = New SqlDataAdapter("select * from item", con1)
ds = New DataSet
da.Fill(ds, "item")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "item"
tables = ds.Tables
view = New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
DataGridView1.AllowUserToAddRows = False
DataGridView1.Columns(0).HeaderText = "Item Id"
DataGridView1.Columns(1).HeaderText = "Item Name"
DataGridView1.Columns(2).HeaderText = "Item Number"
DataGridView1.Columns(3).HeaderText = "GRN Number"
DataGridView1.Columns(4).HeaderText = "Item Qty "
DataGridView1.Columns(5).HeaderText = "Item Max"
DataGridView1.Columns(6).HeaderText = "Item min"
End Sub
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
Dim A As Integer = Me.DataGridView1.Rows(i).Cells(4).Value
Dim c As String = Me.DataGridView1.Rows(i).Cells(6).Value
Dim aa As Double ' string double herawanawa
Dim cc As Double ' string double harawabanwa
aa = CDbl(Val(A))
cc = CDbl(Val(c))
If aa < cc Then
Me.DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.Red
Else
Me.DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.Yellow
End If
Next
End Sub
'***************** export excel *****************************
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
If TextBox1.Text = "" Then
MsgBox("Enter file name")
Return
End If
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Int16, j As Int16
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For x = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(0 + 1, x + 1) = _
DataGridView1.Columns(x).HeaderText
Next
For i = 0 To DataGridView1.RowCount - 1
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 2, j + 1) = _
DataGridView1(j, i).Value.ToString()
Next
Next
Dim path As String
path = "C:\vb\" + TextBox1.Text.Trim + ".xls"
If (path = TextBox1.Text) Then
MsgBox(" no ")
Return
End If
xlWorkBook.SaveAs(path, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue)
xlWorkBook.Close(True, misValue, misValue)
xlApp.Quit()
'MsgBox("misValue")
MsgBox(path)
releaseObject(xlWorkSheet)
releaseObject(xlWorkBook)
releaseObject(xlApp)
MessageBox.Show("File completed to save in your path")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
MessageBox.Show("Exception Occured while releasing object " + ex.ToString())
Finally
GC.Collect()
End Try
End Sub
End Class
You need something along the lines of
Dim formatRange As Excel.Range
formatRange = worksheet.Range("A1", "A3")
formatRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
Just change the range in the brackets to match your range (You can also repeat the second and third lines to cover all different ranges and colors if you need to.
Hope this helps - Find more formatting options here.

export datatable to excel vb.net (new option)

I need export a DataTable to an Excel file using vb.net
I try with two different options, this work but generate conflicts with the labels in the front; somebody know other form to do this?
Dim GridTemp As New GridView()
GridTemp.AllowPaging = False
GridTemp.DataSource = baseIngresos
GridTemp.DataBind()
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=NO_Marcados" + Trim(Ipfechainicio.Text) + "_" + Trim(Ipfechafin.Text) + ".xls")
Response.Charset = "UTF-8"
Response.ContentType = "application/vnd.ms-excel"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
For i As Integer = 0 To GridTemp.Rows.Count - 1
GridTemp.Rows(i).Attributes.Add("class", "textmode")
Next
GridTemp.RenderControl(hw)
Dim style As String = "<style> .textmode{mso-number-format:\#;}</style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
And the other option that I use:
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
Dim htw As New HtmlTextWriter(sw)
Dim pag As New Page()
Dim form As New HtmlForm()
Dim gridV As New GridView()
gridV.EnableViewState = False
gridV.DataSource = baseIngresos
gridV.DataBind()
pag.EnableEventValidation = False
pag.DesignerInitialize()
pag.Controls.Add(form)
form.Controls.Add(gridV)
pag.RenderControl(htw)
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("Content-Disposition", "attachment;filename=NO_Marcados" + Trim(Ipfechainicio.Text) + "_" + Trim(Ipfechafin.Text) + ".xls")
Response.Charset = "UTF-8"
Response.ContentEncoding = Encoding.Default
Response.Write(sb.ToString())
Response.End()
I see that you're using gridview. I'm using a datagridview and used this code:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'FOR HEADERS
For i = 1 To DataGridView1.ColumnCount
xlWorkSheet.Cells(1, i) = DataGridView1.Columns(i - 1).HeaderText
'FOR ITEMS
For j = 1 To DataGridView1.RowCount
xlWorkSheet.Cells(j + 1, i) = DataGridView1(i - 1, j - 1).Value.ToString()
Next
Next
xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file D:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As New OleDbDataAdapter
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=samplelangtowalangya.mdb;"
connection = New OleDbConnection(connetionString)
sql = "update Users set Password = 'new password' where UserID = 'user1'"
Try
connection.Open()
oledbAdapter.UpdateCommand = connection.CreateCommand
oledbAdapter.UpdateCommand.CommandText = sql
oledbAdapter.UpdateCommand.ExecuteNonQuery()
MsgBox("Row(s) Updated !! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
A excel file will be created in the path "D:\vbexcel.xlsx" and save it with the file name vbexcel.xlsx. Also, try reading about Crystal Report. It is widely used in generating reports and open it with excel.

How to use msoShapeStylePresetXX in Shape.ShapeStyle

How can I access msoShapeStylePresetXX in Shape.ShapeStyle?
Im using Visual studio 2012 Visual Basic and Excel (2013 or lower version)
I want to use msoShapeStylePresetXX as a shape style on my shape
Here is my code:
Imports System.Data.OleDb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'AccessdbtestDataSet.country' table. You can move, or remove it, as needed.
Me.CountryTableAdapter.Fill(Me.AccessdbtestDataSet.country)
Dim con As New OleDbConnection
Dim query As String = "SELECT * FROM country"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=accessdbtest.accdb"
con.Open()
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter(query, con)
da.Fill(dt)
DataGridView1.DataSource = ds.Tables(0)
con.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
Dim xlCenter As String = "center"
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Range("A1:D1").MergeCells = True
xlWorkSheet.Range("A2:D2").MergeCells = True
xlWorkSheet.Range("A3:D3").MergeCells = True
xlWorkSheet.Cells(1, 1) = "Republic of the Philippines"
xlWorkSheet.Cells(2, 1) = "NCR"
xlWorkSheet.Cells(3, 1) = "Manila"
xlWorkSheet.Range("A1:A1").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
xlWorkSheet.Range("A2:A2").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
xlWorkSheet.Range("A3:A3").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
For i = 5 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i - 3).Value.ToString()
Next
Next
xlApp.Range("A4").Select()
xlApp.ActiveWindow.FreezePanes = True
Dim shp As Excel.Shape
Dim clLeft As Double
Dim clTop As Double
Dim clWidth As Double
Dim clHeight As Double
Dim cl As Excel.Range
''Dim shpOval As Excel.Shape
xlApp.Range("G5").Select()
cl = xlApp.Range(xlApp.Selection.Address) '<-- Range("C2")
clLeft = cl.Left
clTop = cl.Top
clHeight = cl.Height
clWidth = cl.Width
shp = xlApp.ActiveSheet.Shapes.AddShape(1, clLeft, clTop, 100, 100)
//This line of code is my problem <----------------------------<|
shp.ShapeStyle = msoShapeStylePresetXX
Debug.Print(shp.Left = clLeft)
Debug.Print(shp.Top = clTop)
xlWorkSheet.SaveAs("C:\excel\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file C:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
You just have to add a reference to the "office.dll" in your project (like you did for Excel with Microsoft.Office.Interop.Excel).
With that, VB.net should show you the msoXXX constants:

Align Excel cell to center VB - xlCenter is not declared

Im using Visual Studio 2013 Visual Basic, MS ACCESS 2013, EXCEL 2013
My program Save As the data in my datagrid to excel. I use access 2013 as my database
Here is my code:
Imports System.Data.OleDb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'AccessdbtestDataSet.country' table. You can move, or remove it, as needed.
Me.CountryTableAdapter.Fill(Me.AccessdbtestDataSet.country)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim con As New OleDbConnection
Dim query As String = "SELECT * FROM country"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=accessdbtest.accdb"
con.Open()
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter(query, con)
da.Fill(dt)
DataGridView1.DataSource = ds.Tables(0)
con.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Range("A1:D1").MergeCells = True
xlWorkSheet.Cells(1, 1) = "Republic of the Philippines"
//I got a problem in this line of code. The program gives a message that xlCenter is not declared
xlWorkSheet.Range("H15:H16").VerticalAlignment = xlCenter
For i = 1 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i).Value.ToString()
Next
Next
xlWorkSheet.SaveAs("C:\excel\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file C:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
My problem is The program gives the message:
'xlCenter' is not declared. It may be inaccessible due to its protection level
xlCenter is a member of Microsoft.Office.Interop.Excel.Constants.
Since you assigned Microsoft.Office.Interop.Excel to the name Excel, you can reference that constant like this ...
xlWorkSheet.Range("H15:H16").VerticalAlignment = Excel.Constants.xlCenter
You will need to declare it yourself as its not included in that import( its part of System.Windows)
Const xlCenter = -4108