How to use msoShapeStylePresetXX in Shape.ShapeStyle - vb.net

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:

Related

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.

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

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.

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

How to quit excel application from VB.NET

My program is able to retrieve data from an excel macro 2010 workbook and change contents and save changes made, all using the datagridview within VB.NET. However I'm facing a problem where the program saves but will not close. When I look at the processes in the task manager its still showing Excel 2010 as running. If anyone can help me find a way to quit this application I would greatly appreciate it!
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Imports System.IO
Public Class Form1
Dim SheetList As New ArrayList
Private excelObj As ExcelObject
Private dt As DataTable = Nothing
Dim DS As DataSet
Dim DS2 As DataSet
Dim ds3 As DataSet
Dim ds4 As DataSet
Dim ds5 As DataSet
Dim ds6 As DataSet
Dim ds7 As DataSet
Dim ds8 As DataSet
Dim ds9 As DataSet
Dim ds10 As DataSet
Dim ds11 As DataSet
Dim ds12 As DataSet
Dim ds13 As DataSet
Dim ds14 As DataSet
Dim ds15 As DataSet
Dim ds16 As DataSet
Dim ds17 As DataSet
Dim ds18 As DataSet
Dim MyCommand As OleDb.OleDbDataAdapter
Dim MyCommand2 As OleDb.OleDbDataAdapter
Dim MyCommand3 As OleDb.OleDbDataAdapter
Dim MyCommand4 As OleDb.OleDbDataAdapter
Dim MyCommand5 As OleDb.OleDbDataAdapter
Dim MyCommand6 As OleDb.OleDbDataAdapter
Dim MyCommand7 As OleDb.OleDbDataAdapter
Dim MyCommand8 As OleDb.OleDbDataAdapter
Dim MyCommand9 As OleDb.OleDbDataAdapter
Dim MyCommand10 As OleDb.OleDbDataAdapter
Dim MyCommand11 As OleDb.OleDbDataAdapter
Dim MyCommand12 As OleDb.OleDbDataAdapter
Dim MyCommand13 As OleDb.OleDbDataAdapter
Dim MyCommand14 As OleDb.OleDbDataAdapter
Dim MyCommand15 As OleDb.OleDbDataAdapter
Dim MyCommand16 As OleDb.OleDbDataAdapter
Dim MyCommand17 As OleDb.OleDbDataAdapter
Dim MyCommand18 As OleDb.OleDbDataAdapter
Dim objExcel As New Excel.Application()
Dim objWorkBook As Excel.Workbook = objExcel.Workbooks.Add
Dim objWorkSheet1 As Excel.Worksheet = objExcel.ActiveSheet
Dim objWorkSheet2 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet3 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet10 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet11 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet12 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet13 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet23 As Excel.Worksheet = objExcel.ActiveSheet
Dim objworksheet24 As Excel.Worksheet = objExcel.ActiveSheet
'<TBD make 15 more of these>
Dim MyConnection As OleDb.OleDbConnection
Dim MYDBConnection As DAO.Connection
Public MyWorkspace As DAO.Workspace
Public sizetable As DAO.Recordset
Public MyDatabase As DAO.Database
Public ReadOnly Property Excel() As ExcelObject
Get
If excelObj Is Nothing Then
excelObj = New ExcelObject(txtFilePath.Text)
End If
Return excelObj
End Get
End Property
Sub openExcelfile()
Dim dlg As New OpenFileDialog()
dlg.Filter = "Excel Macro Enabled Files|*.xlsm*|Excel Files|*.xls|Excel 2007 Files|*.xlsx|All Files|*.*"
If dlg.ShowDialog() = DialogResult.OK Then
excelObj = New ExcelObject(dlg.FileName)
txtFilePath.Text = dlg.FileName
btnRetrieve.Enabled = txtFilePath.Text.Length > 0
End If
Dim ExcelSheetName As String = ""
'open the excel workbook and create an object for it
objExcel = CreateObject("Excel.Application")
'do some exception handling on a blank txtfilepath.text
objWorkBook = objExcel.Workbooks.Open(txtFilePath.Text)
Dim i As Integer
i = 1
For Each objWorkSheets In objWorkBook.Worksheets
SheetList.Add(objWorkSheets.Name)
Select Case i
Case 4
objWorkSheet1 = objExcel.Worksheets(objWorkSheets.Name)
Case 5
objWorkSheet2 = objExcel.Worksheets(objWorkSheets.Name)
'ListBox1.Items.Add(objWorkSheets.Name)
'etc
End Select
i = i + 1
Next
End Sub
Sub Write2Excel()
Dim rowindex As Integer
Dim columnindex As Integer
For rowindex = 1 To DataGridView1.RowCount
For columnindex = 1 To DataGridView1.ColumnCount
objWorkSheet1.Cells(rowindex + 4, columnindex + 0) = DataGridView1(columnindex - 1, rowindex - 1).Value
Next
Next
'etc
End Sub
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
openExcelfile()
End Sub
Sub oldretrieve()
' Dim dt As DataTable = Me.Excel.GetSchema()
' cmbTableName.DataSource = (From dr In dt.AsEnumerable() Where Not dr("TABLE_NAME").ToString().EndsWith("$") Select dr("TABLE_NAME")).ToList()
' cmbTableName.Enabled = cmbTableName.Items.Count > 0
' btnGo.Enabled = cmbTableName.Items.Count > 0
' btnDrop.Enabled = cmbTableName.Items.Count > 0
End Sub
Sub RetrieveExcel()
'Create a connection to either 2007 and 2010 xls file
Dim fi As New FileInfo(txtFilePath.Text)
If fi.Extension.Equals(".xls") Then
MyConnection = New OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.8.0; " & "data source=" & txtFilePath.Text & "; " & "Extended Properties=Excel 8.0;")
ElseIf fi.Extension.Equals(".xlsx") Then
MyConnection = New OleDb.OleDbConnection( _
"provider=Microsoft.Ace.OLEDB.12.0; " & _
"data source=" & txtFilePath.Text & "; " & "Extended Properties=Excel 12.0;")
ElseIf fi.Extension.Equals(".xlsm") Then
MyConnection = New OleDb.OleDbConnection( _
"provider=Microsoft.Ace.OLEDB.12.0; " & _
"data source=" & txtFilePath.Text & "; " & "Extended Properties=Excel 12.0;")
End If
'First worksheet'
MyCommand = New OleDbDataAdapter("select * from [1- COTS Worksheet$A4:I150]", MyConnection)
'1- COTS Worksheet.Column(1).Locked = True
DS = New System.Data.DataSet()
MyCommand.Fill(DS)
'---This will prevent the user from editing the size of the rows and columns of the datagrid---'
DataGridView1.AllowUserToResizeColumns = False
DataGridView1.AllowUserToResizeRows = False
DataGridView1.AllowUserToOrderColumns = False
DataGridView1.AllowUserToAddRows = False
DataGridView1.AllowUserToDeleteRows = False
DataGridView1.DataSource = DS.Tables(0).DefaultView
'---The following line makes the column read only---'
DataGridView1.Columns(5).ReadOnly = True
DataGridView1.Columns(6).ReadOnly = True
'''''''if the column is editible then the foreground = blue ''''''''
DataGridView1.Columns(0).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(1).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(2).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(3).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(4).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(7).DefaultCellStyle.ForeColor = Color.Blue
DataGridView1.Columns(8).DefaultCellStyle.ForeColor = Color.Blue
' ''''''This will get rid of the selection blue color for the cells''''''''''''''''''''
DataGridView1.DefaultCellStyle.SelectionBackColor = DataGridView1.DefaultCellStyle.BackColor
DataGridView1.DefaultCellStyle.SelectionForeColor = DataGridView1.DefaultCellStyle.ForeColor
'TABLE TO WRITE TO -
'FIELD TO WRITE TO -
End Sub
Private Sub btnRetrieve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRetrieve.Click
Try
Cursor.Current = Cursors.WaitCursor
RetrieveExcel()
Finally
Cursor.Current = Cursors.Default
End Try
End Sub
Private Sub Form1_Activated(sender As Object, e As EventArgs) Handles Me.Activated
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' btnRetrieve.Enabled = True
MyWorkspace = DAODBEngine_definst.Workspaces(0)
End Sub
Private Sub txtFilePath_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFilePath.TextChanged
btnRetrieve.Enabled = System.IO.File.Exists(txtFilePath.Text)
End Sub
Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
If Me.excelObj IsNot Nothing Then
Me.excelObj.Dispose()
End If
closexlsfile()
End Sub
Private Sub DBFilePath_TextChanged(sender As Object, e As EventArgs) Handles DBFilePath.TextChanged
End Sub
Private Sub BtnBrowseDB_Click(sender As Object, e As EventArgs) Handles BtnBrowseDB.Click
opendbfile()
End Sub
Function opendbfile() As Boolean
Dim dlg As New OpenFileDialog()
dlg.Filter = "DB files|*.mdb|Access DB files|*.accdb|All Files|*.*"
If dlg.ShowDialog() = DialogResult.OK Then
DBFilePath.Text = dlg.FileName
'temporarily myfile will be set to c:/Exceltest/template.mdb
' myfile = "c:/Exceltest/template.mdb"
Try
If DBFilePath.Text <> "" Then
'On Error GoTo errorhandler
MYDBConnection = MyWorkspace.OpenConnection("provider=Microsoft.Ace.OLEDB.12.0; " & "data source=" & txtFilePath.Text)
MyDatabase = MyWorkspace.OpenDatabase(DBFilePath.Text)
sizetable = MyDatabase.OpenRecordset("size", DAO.RecordsetTypeEnum.dbOpenTable)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Function
Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click
'---This Try Finally block with set current cursor to waiting cursor while the program write to excel---'
Try
Cursor.Current = Cursors.WaitCursor
Write2Excel()
Finally
Cursor.Current = Cursors.Default
End Try
End Sub
Sub closexlsfile()
Try
''Do we need to save the file first?
objWorkBook.Save()
objWorkBook.Close()
objExcel.Quit()
'something weird happening on this line
MyConnection.Close()
MyConnection.Dispose()
objWorkBook = Nothing
objExcel = Nothing
Catch
End Try
'TBD the other objworksheets get closed here
End Sub
Private Sub closexls_Click(sender As Object, e As EventArgs) Handles closexls.Click
closexlsfile()
NAR(objWorkSheet1)
NAR(objWorkSheet2)
NAR(objworksheet3)
NAR(objworksheet10)
NAR(objworksheet11)
NAR(objworksheet12)
NAR(objworksheet13)
NAR(objworksheet23)
NAR(objworksheet24)
objWorkBook.Close(False)
NAR(objWorkBook)
NAR(MyConnection)
objExcel.Quit()
NAR(objExcel)
Debug.WriteLine("Sleeping...")
System.Threading.Thread.Sleep(5000)
Debug.WriteLine("End Excel")
End Sub
'---This is a method that I found of MSDN to quit an office application but it doesn't seem to work---'
Private Sub NAR(ByVal obj As Object)
Try
While (System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) > 0)
End While
Catch
Finally
obj = Nothing
End Try
End Sub
End Class
You obviously have a lot of code and I can't go through all of that. However I dealt with this problem in the past. It is usually due to an unreleased object of some kind. For example lots of code samples from the intertubes suggests that you do things like
objWorkBook = objExcel.Workbooks.Open(txtFilePath.Text)
This is potentially dangerous, you should never have more than ONE . in a single right hand value. Instead go for something like
Workbooks wrkbks = objExcel.Workbooks
objWorkBook = wrkbks.Open(txtFilePath.Text)
Otherwise there will be memory allocated for the WorkBooks that isn't explicitly released. This is really a pain to go through all your code base once you've discovered this, but it solved the problem for me.
Your NAR sub should have it handled, but I far prefer Marshal.FinalReleaseComObject method - no loop required. You need to make sure all instances have been addressed - like in the closexlsfile() method you do not call NAR for these Com objects. I suggest some code cleanup.