There is a little bit of code needed in addition to what you might hope would be a simple operation of opening an Excel file using a .NET program, which is explained at The proper way to dispose Excel com object using VB.NET? I've used that in the code below.
The Office Interop stuff can be tedious to get the correct variable types for - you can get Visual Studio to help you by using Option Strict On
and Option Infer On
. (I have them set as defaults for new projects, so I wouldn't normally have them showing in the code.)
When you're putting filenames and paths together, it is easy to get the \s in a muddle, so Path.Combine
can be used so that you don't have to worry about leaving, or not, a trailing directory separator in.
There's no need to hard-code the desktop directory path, as there is a function to get it for you and it will automatically change for each user on the computer.
Onto actually saving the file, there are many parameters for the WorkBook.Save method, and so I took the easy route of using a named parameter to tell it the format to save in. It will automatically add the correct filename extension for the type of file being saved.
So...
Option Strict On
Option Infer On
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel
Imports System.IO
Public Class Form1
Private Sub SaveExcelAsTextOperation(src As String, dest As String)
Dim app As New Excel.Application
Dim book = app.Workbooks.Open(src)
book.SaveAs(dest, FileFormat:=XlFileFormat.xlCSV)
book.Close()
app.Quit()
End Sub
Private Sub SaveExcelAsText(src As String, dest As String)
' from: The proper way to dispose Excel com object using VB.NET? https://stackoverflow.com/a/38111107
SaveExcelAsTextOperation(src, dest)
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
Private Sub btnExcelSaveAs_Click(sender As Object, e As EventArgs) Handles btnExcelSaveAs.Click
Dim filename1 = txtBoxExcelFileNameString.Text
Dim workDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
Dim source = Path.Combine(workDirectory, filename1 & ".xlsx")
Dim destination = Path.Combine(workDirectory, filename1)
SaveExcelAsText(source, destination)
End Sub
End Class
does what I think you wanted. There is an Excel save dialog which appears; I am sure you can find an option to not show that.