Type expected error VB.Net - vb.net

Error ImagePlease assist, I get a "Type expected" error on my code for a windows based application. I get the error on this line "Dim objSW As New StreamWriter(objFS)"
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strFileName As String = My.Application.Info.DirectoryPath & "\empout_fixed.txt"
Dim objFS As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Dim objSW As New StreamWriter(objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single
strEmpName = “Thabo Lereko”
intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99
' Write out the record to the file ...
objSW.WriteLine(strEmpName.PadRight(20) &
intDeptNbr.ToString.PadLeft(4) &
Space(5) &
strJobTitle.PadRight(21) &
Format(dtmHireDate, "M/d/yyyy").PadRight(10) &
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox("Record was written to the output file.")
objSW.Close()
End Sub
End Class

The problem is that you have named your project "StreamWriter", which causes "StreamWriter" to refer to the namespace of the project. Maybe you should use more a bit more descriptive project names in the future just for clarity?
You can fix this by referring to the real StreamWriter with namespace:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strFileName As String = My.Application.Info.DirectoryPath & "\empout_fixed.txt"
Using objFS As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Using objSW As New System.IO.StreamWriter(objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single
strEmpName = “Thabo Lereko”
intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99
' Write out the record to the file ...
objSW.WriteLine(strEmpName.PadRight(20) &
intDeptNbr.ToString.PadLeft(4) &
Space(5) &
strJobTitle.PadRight(21) &
Format(dtmHireDate, "M/d/yyyy").PadRight(10) &
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox("Record was written to the output file.")
End Using
End Using
End Sub
End Class
Ps. Added the using-statements that should always be used with iDisposable-objects. Removed the unnecessary close-call also.

Related

Update Button for Access Database via DataGridView Using OLEDB in VB.NET (Visual Studio 2013)

I have linked an Access database to my program. It populates the DataGridView as it is intended to so that part of the program works. However the new data that i add to my DataGridView wont show up and I don't know what is wrong with my code.
Can anyone see anything wrong or something I've missed out that would cause the code not to function as desired? Thank you in advance :)
Imports System.Data.OleDb
Public Class Form1
Dim j As OleDbConnection
Dim a As OleDbDataAdapter
Dim s As DataSet
Dim lokasidb As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call jaringan()
a = New OleDbDataAdapter("Select * From datadairy", j)
s = New DataSet
s.Clear()
a.Fill(s, "datadairy")
DataGridDairy.DataSource = (s.Tables("datadairy"))
End Sub
Private Sub eksekusiSql(ByVal Sql As String)
Dim objcmd As New System.Data.OleDb.OleDbCommand
Call jaringan()
Try
objcmd.Connection = j
objcmd.CommandType = CommandType.Text
objcmd.CommandText = Sql
objcmd.ExecuteNonQuery()
objcmd.Dispose()
MsgBox("The new data successfully saved", vbInformation)
Catch ex As Exception
MsgBox("The new data is failed to save", vbInformation)
End Try
End Sub
Sub jaringan()
lokasidb = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\19106060045_Tugas Modul 5.accdb"
j = New OleDbConnection(lokasidb)
If j.State = ConnectionState.Closed Then j.Open()
End Sub
Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
Dim No As String = TextNo.Text
Dim Jenis_Susu_Sapi As String = TextSusu.Text
Dim Jenis_Olahan As String = TextOlahan.Text
Dim Harga_per_kg As String = TextHarga.Text
Dim Tempat_Penjualan As String = TextPasar.Text
Dim Sql_Simpan_Dairy As String = "Insert into datadairy (No, Jenis_Susu_Sapi, Jenis_Olahan, Harga_per_kg, Tempat_Penjualan) values (" + No + ",'" + Jenis_Susu_Sapi + "','" + Jenis_Olahan + "','" + Harga_per_kg + "','" + Tempat_Penjualan + "')"
eksekusiSql(Sql_Simpan_Dairy)
ShowDairydata()
End Sub
Public Sub ShowDairydata()
Call jaringan()
a = New OleDbDataAdapter("Select * from datadairy", j)
s = New DataSet
s.Clear()
a.Fill(s, "datadairy")
DataGridDairy.DataSource = (s.Tables("datadairy"))
End Sub
After adding new data to your database, just use
'DataGridDairy.Databind()'
to refresh.

How to create a progress bar that updates simultaneously with a file transfer

As the title implies, I am trying to create a progress bar that updates with a file transfer. I am currently using Visual Studio 2019. I have been through dozens of articles and videos all claiming to do just this. After many days of testing, I have gotten close, but the progress bar will still only update after the file transfer is complete. I am using multi threading techniques to accomplish just this much. I would very much appreciate if someone could just lay it down for me on how to do this. Here is my code so far. It doesn't really help for making it but you can at least see what I am trying to achieve. I also left out some large chunks of commented out test script.
Summary of what I need to is: Create a script that will copy the specified directory and all sub directories. While doing this I would like the progress bar to move with the file transfer.
Imports System.ComponentModel
Imports System.Threading
Imports System
Imports System.IO
Public Class Form1
Private Sub BtnStartTransfer_Click(sender As Object, e As EventArgs) Handles btnStartTransfer.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Delegate Sub DelegateProgressBarMax(ByVal check As Integer)
Private Sub ProgressBarUpdate(ByVal check As Integer)
If pBar1.InvokeRequired = True Then
Invoke(Sub() pBar1.Value = check)
Else
pBar1.Value = check
End If
End Sub
Private Delegate Sub DelegateUpdateOutput(ByVal check2 As String)
Private Sub OutputUpdate(ByVal check2 As String)
If txtOutput.InvokeRequired = True Then
Invoke(Sub() txtOutput.Text = txtOutput.Text & check2 & Environment.NewLine)
Else
txtOutput.Text = txtOutput.Text & check2
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim getCopyFrom As String = txtCopyFrom.Text
Dim getCopyTo As String = txtCopyTo.Text
Dim splitUser() As String = getCopyFrom.Split("\")
Dim finalValue As String = splitUser.Length - 1
Dim stringValue As String = CStr(splitUser(finalValue))
Dim getUser As String
'If MsgBox("Is this the correct user?: " & stringValue, vbYesNo + vbQuestion) = vbYes Then
' getUser = stringValue
'Else
' getUser = InputBox("Enter in the correct Username")
'End If
Dim checkCopyFrom As New IO.DirectoryInfo(getCopyFrom)
Dim checkCopyTo As New IO.DirectoryInfo(getCopyTo)
If checkCopyFrom.Exists Then
Else
MsgBox("The location you are trying to copy from does not exist.")
Exit Sub
End If
If checkCopyTo.Exists Then
Else
MsgBox("The location you are trying to copy to does not exist.")
Exit Sub
End If
'Copying the Desktop folder
Dim dirDesktop = getCopyFrom & "\Desktop"
Dim getDir = IO.Directory.GetFiles(dirDesktop, "*", IO.SearchOption.AllDirectories)
Dim fileTotal As Integer = getDir.Length
Dim filesTransferred As Integer = 0
Dim di As New DirectoryInfo(dirDesktop)
Dim fiArr As FileInfo() = di.GetFiles("*", SearchOption.AllDirectories)
Dim diArr As DirectoryInfo() = di.GetDirectories("*", IO.SearchOption.AllDirectories)
Dim fri As FileInfo
Dim fol As DirectoryInfo
For Each fri In fiArr
filesTransferred += 1
BackgroundWorker1.ReportProgress(CInt(filesTransferred * 100 \ fiArr.Length), True)
OutputUpdate(fri.Name)
'File.Copy(dirDesktop & "\" & fri.Name, getCopyTo & "\" & fri.Name, True)
'My.Computer.FileSystem.CopyDirectory(getCopyFrom & "\Desktop", getCopyTo & "\Users\" & getUser & "\Desktop", False)
Next fri
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
pBar1.Value = e.ProgressPercentage
End Sub

How to get line number from a text file in vb.net

I am making a program where i have 2 text files and i want 2 get one line from each text file like this
Dim pathlocal as string= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Test\"
Dim reader As New System.IO.StreamReader(pathlocal & "to.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
For Each file In allLines
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(file).Name) Then
'Get line number of from.txt where you found file.name
End If
End If
Next
I appreciate the help(and pls try 2 make it simple sorry but i am not that good THANX)
This might help you:
Imports System.IO
Imports System
Imports System.Collections.Generic
Public Class Form1
Dim path As String = "Your Path"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim indxto As Integer = 0
Dim indxfrom As Integer = 0
Dim allLinesto As List(Of String) = File.ReadAllLines(path & "\" & "to.txt").ToList
Dim allLinesfrom As List(Of String) = File.ReadAllLines(path & "\" & "from.txt").ToList
For Each line As String In allLinesto
indxto = allLinesto.IndexOf(line)
'Debug.Print(line & " " & indxto.ToString)
For Each item As String In allLinesfrom
indxfrom = allLinesto.IndexOf(item)
If line = item Then
Debug.Print(item & " " & indxfrom.ToString)
End If
Next
Next
End Sub
End Class
You can instantiate a couple of Integer typed variables to help with this. One stores the line number as you iterate through the list and the other stores the line number you are seeking. Plus, by changing your For Each approach to a Do Until or Do While approach you could potentially speed things up if the target is found prior to the last line of the file.
Dim intLineNumber As Integer = -1
Dim intLineCursor As Integer
Do Until (intLineCursor = allLines.Count OrElse intLineNumber <> -1)
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(allLines(intLineCursor)).Name) Then
intLineNumber = intLineCursor '+ 1 if you are displaying to a user since the lower bound is 0 based.
End If
'Increment the cursor variable.
intLineCursor += 1
Loop

Code behind for print?

I have a report that I need to print after a sale has completed.
I am having issues with the length and printing when using PrintForm and PrintDocument components however if I right click and select Print from the list the report prints perfectly.
Is there any way that I could write code in my form load event that would imitate the right click print?
Ive been struggling with this part of my project for ages now and the whole thing is now way behind schedule.
My Code for the whole Receipt form page is:
Imports System.Data.OleDb
Imports System.IO
Imports System.Drawing.Printing
Public Class Receipt
Public PicLocation As String
Dim Ctrl1, Ctrl2 As Control
Dim CN As New OleDb.OleDbConnection
Dim CMD As New OleDb.OleDbCommand
Dim DataR As OleDb.OleDbDataReader
'To display into datagrid purpose
Dim dataS As New DataSet
Dim dataAd As New OleDb.OleDbDataAdapter
Public SqlStr, SqlStr1, DBPath, DBStatus, SearchBox As String
Dim X, Y, SqlH, Onh As Integer
Dim SqlUser As String
Dim DataP As Decimal
Dim Balance As Integer
Private Sub Receipt_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'ProductListDataSet' table.
DBPath = (Application.StartupPath & "\ProductList.accdb")
If CN.State = ConnectionState.Open Then
CN.Close()
DBStatus = ("Not Connected")
End If
SqlStr = ("Provider = Microsoft.ACE.OLEDB.12.0;Data Source =" & DBPath)
CN.ConnectionString = SqlStr
CN.Open()
Onh = Nothing
lblTime.Text = DateAndTime.Now
lblUser.Text = Login.userTB.Text
Dim sql As String
sql = "SELECT * Receipt"
Me.ReceiptTableAdapter.ClearBeforeFill = True
Me.ReceiptTableAdapter.Connection = CN
Me.ReceiptTableAdapter.Connection.CreateCommand.CommandText = sql
Me.ReceiptTableAdapter.Fill(Me.ProductListDataSet.Receipt)
Me.ReportViewer1.RefreshReport()
Me.Refresh()
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
With Me.PrintForm1
.PrintAction = Printing.PrintAction.PrintToPrinter
Dim MyMargins As New Margins
With MyMargins
.Left = 0
.Right = 0
.Top = 0
.Bottom = 0
End With
.PrinterSettings.DefaultPageSettings.Margins = MyMargins
.Print(Me, PowerPacks.Printing.PrintForm.PrintOption.CompatibleModeClientAreaOnly)
End With
End Sub
End Class

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.