prompt for opening a save dialog for excel file using vb.net - vb.net

Iam using visual studio 2012,
i would like to open "save dialog" to choose where to save my file instead of using fixed path,
the following code is a sample of what i would like to use it in:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlsWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlsWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim xls As New Microsoft.Office.Interop.Excel.Application
Dim resourcesFolder = IO.Path.GetFullPath(Application.StartupPath & "\Resources\")
Dim fileName = "book1.xlsx"
xlsWorkBook = xls.Workbooks.Open(resourcesFolder & fileName)
xlsWorkSheet = xlsWorkBook.Sheets("a")
xlsWorkSheet.Cells(1, 1) = TextBox1.Text
xlsWorkBook.SaveAs("C:\output\book1.xlsx")
xlsWorkBook.Close()
xls.Quit()
End Sub
i would like to change this path "C:\output\book1.xlsx" to save dialog, so i can choose where to save it manually.
thanks alot..

Like this, don't forget to dispose of com objects with the Marshal class like I added.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xls As New Microsoft.Office.Interop.Excel.Application
Dim xlsWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlsWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim resourcesFolder = IO.Path.GetFullPath(Application.StartupPath & "\Resources\")
Dim fileName = "book1.xlsx"
xlsWorkBook = xls.Workbooks.Open(resourcesFolder & fileName)
xlsWorkSheet = xlsWorkBook.Sheets("a")
xlsWorkSheet.Cells(1, 1) = TextBox1.Text
Using sfd As New SaveFileDialog
If sfd.ShowDialog() = DialogResult.OK Then
xlsWorkBook.SaveAs(sfd.FileName)
MessageBox.Show(sfd.Filename)
End If
End Using
xlsWorkBook.Close()
xls.Quit()
Marshal.FinalReleaseComObject(xlsWorkSheet)
Marshal.FinalReleaseComObject(xlsWorkBook)
Marshal.FinalReleaseComObject(xls)
End Sub

A little more comprehensive way to open the Save As Dialog than OneFineDay's answer (using the same method).
This opens the Save As dialog using a designated directory, filename, extension type, and window title; it also prompts before overwritting any existing files.
Dim dir as String = "C:\output\"
Dim fName As String = "Book1"
Using sfd As New SaveFileDialog
sfd.InitialDirectory = dir
sfd.Title = "Save As"
sfd.OverwritePrompt = True
sfd.FileName = fName
sfd.DefaultExt = ".xlsx"
sfd.Filter = "Excel Workbook(*.xlsx)|"
sfd.AddExtension = True
If sfd.ShowDialog() = DialogResult.OK Then
xlsWorkBook.SaveAs(sfd.FileName)
End If
End Using

Add an openfiledialog to your form and then ...
With OpenFileDialog1
.Title = " whatever"
.InitialDirectory = "c:\"
.Multiselect = False
If .ShowDialog() = DialogResult.OK Then
xlsWorkBook.SaveAs(.FileName)
End If
End With

You can use this :
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlsWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlsWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim xls As New Microsoft.Office.Interop.Excel.Application
Dim resourcesFolder = IO.Path.GetFullPath(Application.StartupPath & "\Resources\")
Dim fileName = "book1.xlsx"
xlsWorkBook = xls.Workbooks.Open(resourcesFolder & fileName)
xlsWorkSheet = xlsWorkBook.Sheets("a")
xlsWorkSheet.Cells(1, 1) = TextBox1.Text
xlsWorkBook.SaveAs("C:\output\book1.xlsx")
xls.Application.DisplayAlerts = False
xlsWorkBook.Close()
xls.Quit()
End Sub

Related

Vb.net - FolderBrowserDialog

I am having some troubles with FolderBrowserDialog
I've tried all the post I could find here and I'm almost there in terms of what I want.
following is my code:
Private Sub ButtonBrowseOutput_Click(sender As Object, e As EventArgs) Handles ButtonBrowseOutput.Click
Dim dialog = New FolderBrowserDialog()
dialog.SelectedPath = Application.StartupPath
If DialogResult.OK = dialog.ShowDialog() Then
TextBoxShowOutput.Text = dialog.ToString & "/helloforum" & ".txt"
End If
End Sub
would give me something like this:
System.Windows.Forms.FolderBrowserDialog/helloforum.txt
Where I want it to give it for example:
c:/users/sexyname/desktop/helloforum.txt
TextBoxShowOutput.Text = dialog.ToString & "/helloforum" & ".txt"
Must be:
TextBoxShowOutput.Text = dialog.SelectedPath & "/helloforum" & ".txt"
SelectedPath - Gets or sets the path selected by the user.
dialog.SelectedPath & "/helloforum.txt"
Just for your knowledge
Private Sub AbsolutePathOfDialogBoxes()
Dim dlgFolder = New FolderBrowserDialog
Dim dlgOpenFile = New OpenFileDialog
Dim dlgSaveFile = New SaveFileDialog
Dim absolutePath As String
'/*-----------------------------------*/'
absolutePath = dlgFolder.SelectedPath
absolutePath = dlgOpenFile.FileName
absolutePath = dlgSaveFile.FileName
'/*-----------------------------------*/'
End Sub
Happy Coding

Embed multiple excel files in a word document, displayed as icons

I am able to copy a single excel file into a word document, displayed as an icon. But when i select multiple files from a folder, what happens is each of the files get copied into a new word document. In other words, I am unable to embed multiple files at a time into a single word document.
Also here in my code i have to create a bookmark from begining into the word document. I want to create the bookmark in the word document dynamically through code.
Could anyone please guide me how i can create bookmarks dynamically through code and also how can i embed many files at a time into a single word document.
Here is my working code that embeds only one file at a time.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog
ofd.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
ofd.Filter = "Excel Files (*.xls;xlsx)|*.xls;xlsx"
ofd.FilterIndex = 2
ofd.RestoreDirectory = True
ofd.Multiselect = True
Dim Files As String = ofd.InitialDirectory
If ofd.ShowDialog() = DialogResult.OK Then
For Each Files In ofd.FileNames
Dim filename As String = ofd.FileName
Dim oWord As Word.Application = New Word.Application()
Dim oWordDoc As Word.Document = oWord.Documents.Open("C:\testing.doc", False)
Dim oMissing As Object = System.Reflection.Missing.Value
oWord.Visible = True
'ICON LABEL CAN BE THE NAME OF THE FILE,
'ITS THE NAME DISPLAYED BESIDES THE EMBEDDED DOCUMENT
Dim oIconLabel As Object = filename
'THE BOOKMARK WHERE THE FILE NEEDS TO BE EMBEDDED
Dim oBookMark As Object = "ssss"
'//THE LOCATION OF THE FILE
Dim oFileDesignInfo As Object = filename
'//OTHER VARIABLES
Dim oClassType As Object = "Word.Document.8"
Dim oTrue As Object = True
Dim oFalse As Object = False
'Dim oMissing As Object = System.Reflection.Missing.Value
Dim oIconFileName As Object = oMissing
'METHOD TO EMBED THE DOCUMENT
oWordDoc.Bookmarks.Item(oBookMark).Range.InlineShapes.AddOLEObject(oClassType, oFileDesignInfo, _
oFalse, oTrue, oIconFileName, oMissing, oIconLabel, oMissing)
Next
End If
End Sub
Your code to open a new word instance and load the document is within the loop - move it out of the loop so you only run it once.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog
ofd.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
ofd.Filter = "Excel Files (*.xls;xlsx)|*.xls;xlsx"
ofd.FilterIndex = 2
ofd.RestoreDirectory = True
ofd.Multiselect = True
Dim Files As String = ofd.InitialDirectory
If ofd.ShowDialog() = DialogResult.OK Then
Dim oWord As Word.Application = New Word.Application()
Dim oWordDoc As Word.Document = oWord.Documents.Open("C:\testing.doc", False)
Dim oMissing As Object = System.Reflection.Missing.Value
oWord.Visible = True
For Each Files In ofd.FileNames
'*************
'rest of code....
'*************
Next
End If
End Sub
Finally have done it successfully...Here is the working code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog
ofd.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
ofd.Filter = "Excel Files (*.xls;xlsx)|*.xls;xlsx"
ofd.FilterIndex = 2
ofd.RestoreDirectory = True
ofd.Multiselect = True
Dim Files As String
If ofd.ShowDialog() = DialogResult.OK Then
Dim oWord As Word.Application = New Word.Application()
Dim oWordDoc As Word.Document = oWord.Documents.Open("C:\testing.doc", True)
Dim oBookmark As Object = oWordDoc.Bookmarks.Add("Bookmark")
Dim oMissing As Object = System.Reflection.Missing.Value
oWord.Visible = True
For Each Files In ofd.FileNames
'ICON LABEL CAN BE THE NAME OF THE FILE,
'ITS THE NAME DISPLAYED BESIDES THE EMBEDDED DOCUMENT
Dim oIconLabel As Object = Path.GetFileName(Files)
'//INCASE WE NEED THE EMBEDDED DOCUMENT TO BE DISPLAYED AS A SPECIFIC ICON,
'//WE NEED TO SPECIFY THE LOCATION OF THE ICON FILE
'//ELSE SET IT TO oMissing VALUE
'Dim oIconFileName As Object = "C:\\Document and Settings\\IconFile.ico"
'//THE LOCATION OF THE FILE
Dim oFileDesignInfo As Object = Files
'//OTHER VARIABLES
Dim oClassType As Object = "Word.Document.8"
Dim oTrue As Object = True
Dim oFalse As Object = False
'Dim oMissing As Object = System.Reflection.Missing.Value
Dim oIconFileName As Object = oMissing
'//METHOD TO EMBED THE DOCUMENT
oWordDoc.Bookmarks.Item(oBookMark).Range.InlineShapes.AddOLEObject(oClassType, oFileDesignInfo, _
oFalse, oTrue, oIconFileName, oMissing, oIconLabel, oMissing)
Next
End If
Me.Close()
End Sub

Print Preview not displaying file

I am working on a menu strip Print Preview event. i worked out the following procedure to view a pdf file located in the same path as my workbook.
Private WithEvents docPrint As New PrintDocument()
' Declare a string to hold the entire document contents.
Private documentContents As String
' Declare a variable to hold the portion of the document that
' is not printed.
Private stringToPrint As String
Private Sub ReadDocument()
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
Dim stream As New FileStream(docName, FileMode.Open)
Try
Dim reader As New StreamReader(stream)
Try
documentContents = reader.ReadToEnd()
Finally
reader.Dispose()
End Try
Finally
stream.Dispose()
End Try
stringToPrint = documentContents
End Sub
Private Sub prnPrvStripCustomRange_Click(sender As Object, e As EventArgs) Handles prnPrvStripCustomRanges.Click
ReadDocument()
prnPrvCustomRanges.Document = docPrint
prnPrvCustomRanges.ShowDialog()
End Sub
The dialog pops up on click, but my document page is blank. I have another event for printing and that one prints the same document. So I don't understand what I am doing wrong on my preview.
Here is my print procedure:
Private Sub prnCustonPages_Click(sender As Object, e As EventArgs) Handles prnCustonPages.Click
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
prnPrtCustomRanges.Document = docPrint
prnPrtCustomRanges.PrinterSettings = docPrint.PrinterSettings
prnPrtCustomRanges.AllowSomePages = True
If prnPrtCustomRanges.ShowDialog = DialogResult.OK Then
docPrint.PrinterSettings = prnPrtCustomRanges.PrinterSettings
docPrint.Print()
End If
End Sub

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.

How to add else statement into downloading code?

I'm making a file downloader and I want it to download files to either my selected directoy or default directory.
Downloading code is here:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
Button1.Text = "Updating..."
WebBrowser1.Visible = True
Dim uri As System.Uri = New System.Uri("http://199.91.154.170/e9f6poiwfocg/pei02c8727sa720/Ultra+v08.zip")
Dim webclient As System.Net.WebClient = New System.Net.WebClient()
Dim path As String =
If apppath = Nothing then
New String(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test\\Test.zip"))
Else New String
(apppath)
End if
Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(path)
If Not System.IO.Directory.Exists(fileInfo.Directory.FullName) Then
System.IO.Directory.CreateDirectory(fileInfo.Directory.FullName)
End If
AddHandler webclient.DownloadFileCompleted, AddressOf webclient_DownloadDataCompleted
webclient.DownloadFileAsync(uri, path)
End Sub
Private Sub
And user selected path apppath is defined here:
If apppath = "" Then
Dim dialog As New FolderBrowserDialog()
dialog.RootFolder = Environment.SpecialFolder.Desktop
dialog.SelectedPath = Path.Combine(Environment.GetFolderPath( _
Environment.SpecialFolder.ApplicationData))
dialog.Description = "Select directory where to install the files"
If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
apppath = dialog.SelectedPath
End If
My.Computer.FileSystem.WriteAllText(apppath & " apppath.txt", apppath, False)
End If
How to fix Dim path As String else statement?
Thanks in advance!
If I am understanding your question correctly then I believe there is a simple solution, which is this:
Dim path As String
If apppath = Nothing then
path = New String(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test\Test.zip"))
Else New String
path = apppath
End if
If I have not understood your requirements correctly, then please provide more information.