Creating a excel spreadsheet in vb.net Application not defined - excel

I am trying to create an Office 365 excel spreadsheet using vb.net. I have added the following reference. Microsoft,Office 16.0 Object Library to the project.
Anything with Excel. Errors as not defined.
What's missing?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim objApp As Excel.Application
Dim objBook As Excel._Workbook
Dim objBooks As Excel.Workbooks
Dim objSheets As Excel.Sheets
Dim objSheet As Excel._Worksheet
Dim range As Excel.Range
' Create a new instance of Excel and start a new workbook.
objApp = New Excel.Application()
objBooks = objApp.Workbooks
objBook = objBooks.Add
objSheets = objBook.Worksheets
objSheet = objSheets(1)

You have two options to resolve your issue:
Option 1: Add Imports statement:
Imports Excel = Microsoft.Office.Interop.Excel
Option 2: Specify the namespace
Dim objApp As Microsoft.Office.Interop.Excel.Application
Dim objBook As Microsoft.Office.Interop.Excel._Workbook
Try the following:
Add a Module to your project (name: HelperExcel.vb)
HelperExcel.vb
'Add Reference
'Project => Add Reference => COM => Microsoft Excel 16.0 Object Library
Imports Excel = Microsoft.Office.Interop.Excel
Module HelperExcel
Public Sub CreateExcelWorkbook(filename As String)
Dim oMissing As Object = System.Reflection.Missing.Value
Dim excelApp As Excel.Application = Nothing
Dim excelWorkbook As Excel.Workbook = Nothing
Dim excelWorksheet As Excel.Worksheet = Nothing
Try
'create New instance
excelApp = New Excel.Application()
'suppress displaying alerts (such as prompting to overwrite existing file)
excelApp.DisplayAlerts = False
'set Excel visability
excelApp.Visible = True
'disable user control while modifying the Excel Workbook
'to prevent user interference
'only necessary if Excel application Visibility property = true
'excelApp.UserControl = false
'add workbook
excelWorkbook = excelApp.Workbooks.Add()
'add a worksheet And set the value to the New worksheet
excelWorksheet = excelWorkbook.Sheets.Add()
'indices are 1-based in Excel; A1 = Cells(1,1)
'excelWorksheet.Cells(1, "A") = "Product Code"
'excelWorksheet.Cells(1, "B") = "Product Description"
excelWorksheet.Cells(1, 1) = "Product Code"
excelWorksheet.Cells(1, 2) = "Product Description"
If excelApp IsNot Nothing AndAlso excelWorkbook IsNot Nothing Then
'save Workbook - if file exists, overwrite it
excelWorkbook.SaveAs(filename, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value)
End If
Catch ex As Exception
Debug.WriteLine("Error (CreateExcelWorkbook): " & ex.Message)
Throw ex
Finally
If excelWorkbook IsNot Nothing Then
excelWorkbook.Close()
excelWorksheet = Nothing
excelWorkbook = Nothing
End If
If excelApp IsNot Nothing Then
excelApp.Quit()
'release all resources
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp)
End If
End Try
End Sub
End Module
Usage:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnRun.Click
'write file to Documents folder (ex: C:\Users\<username>\Documents\TestExcel.xlsx)
Dim filename As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "TestExcel.xlsx")
HelperExcel.CreateExcelWorkbook(filename)
End Sub

Related

How to export data from multiple emails to Excel workbook but different worksheets?

I want to export data from selected Outlook emails to a workbook. Each email's data (subject, body, etc.) should be stored in a different worksheet.
I'm trying to edit this macro because it is almost what I need—and especially the part of olFormatHTML and WordEditor—because of split.
The idea is
Select multiple emails in Outlook
Open file path
Data for each email selected will be stored in a single worksheet from file opened
The issue with the macro is in this third part
From the selected items, the macro does a loop and just takes the first email selected,
The data is stored in different workbooks; it should be stored in the same workbook that I opened.
Public Sub SplitEmail()
Dim rpl As Outlook.MailItem
Dim itm As Object
Dim sPath As String, sFile As String
Dim objDoc As Word.Document
Dim txt As String
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim i As Long
Dim x As Long
'----------------------------
Dim myOlExp As Outlook.Explorer
Dim myOlSel As Outlook.Selection
Set myOlExp = Application.ActiveExplorer
Set myOlSel = myOlExp.Selection
For x = 1 To myOlSel.Count
'----------------------------------------------
Set itm = GetCurrentItem() 'A)I think the issuefrom selecting 1 item is located here
'|||||||||||||||||||||||||||||||||||||||||
sPath = "C:\Users\Ray\"
sFile = sPath & "Macro.xlsm"
If Not itm Is Nothing Then
Set rpl = itm.Reply
rpl.BodyFormat = olFormatHTML
'rpl.Display
End If
Set objDoc = rpl.GetInspector.WordEditor
txt = objDoc.Content.Text
'||||||||||||||||||||||||||||||||||||||||||||||
Set xlApp = CreateObject("Excel.application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(sFile) 'B) tried to move it to the beginning and macro doesn't work
'||||||||||||||||||||||||||||||||||||||||||||||
For i = LBound(Split(txt, Chr(13)), 1) To UBound(Split(txt, Chr(13)), 1)
wb.Worksheets(x).Range("A" & i + 1).Value = Split(txt, Chr(13))(i) 'B)emails in diferrent sheet but no same workbook
Next i
'------------------------------------------------------
Next x
End Sub
Function GetCurrentItem() As Object
Dim objApp As Outlook.Application
Set objApp = Application
On Error Resume Next
Select Case TypeName(objApp.ActiveWindow)
Case "Explorer"
Set GetCurrentItem = objApp.ActiveExplorer.Selection.item(1)
Case "Inspector"
Set GetCurrentItem = objApp.ActiveInspector.CurrentItem
End Select
GetCurrentItem.UnRead = False
Set objApp = Nothing
End Function
I made an update to this macro
as macro do loop in For x it open the file x times,
and then close it and open again instead of working on the first workbook opened
but the macro leaves open instances
here is the current code
Public Sub SplitEmail()
Dim rpl As Outlook.MailItem
Dim itm As Object
Dim sPath As String, sFile As String
Dim objDoc As Word.Document
Dim txt As String
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim i As Long
Dim x As Long
'----------------------------
Dim myOlExp As Outlook.Explorer
Dim myOlSel As Outlook.Selection
Set myOlExp = Application.ActiveExplorer
Set myOlSel = myOlExp.Selection
For x = 1 To myOlSel.Count
'----------------------------------------------
Dim objApp As Outlook.Application
Dim GetCurrentItem As Object
Set objApp = Application
On Error Resume Next
Select Case TypeName(objApp.ActiveWindow)
Case "Explorer"
Set GetCurrentItem = objApp.ActiveExplorer.Selection.item(x)
Case "Inspector"
Set GetCurrentItem = objApp.ActiveInspector.CurrentItem
End Select
GetCurrentItem.UnRead = False
Set objApp = Nothing
'-----------------------------------------------
Set itm = GetCurrentItem
sPath = "C:\Users\Ray\"
sFile = sPath & "Macro.xlsm"
If Not itm Is Nothing Then
'de lo contrario, se crea un Reply del correo en formato HTML
Set rpl = itm.Reply
rpl.BodyFormat = olFormatHTML
'rpl.Display
End If
Set objDoc = rpl.GetInspector.WordEditor
txt = objDoc.Content.Text
'||||||||||||||||||||||||||||||||||||||||||||||
Set xlApp = CreateObject("Excel.application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(sFile)
xlApp.Windows("Macro.xlsm").Activate
'Set wb = ActiveWorkbook
'||||||||||||||||||||||||||||||||||||||||||||||
For i = LBound(Split(txt, Chr(13)), 1) To UBound(Split(txt, Chr(13)), 1)
wb.Worksheets(x).Range("A" & i + 1).Value = Split(txt, Chr(13))(i)
Next i
xlApp.Windows("Macro.xlsm").Close SaveChanges:=True
xlApp.Workbook.Close SaveChanges:=False
'------------------------------------------------------
Next x
'------------------------------------------------------
'the instances should closed but not working, instances are empty
For Each wb In xlApp
wb.Close SaveChanges:=False
Next
End Sub
done, I added xlApp.Quit after saving files and deleted the last part For Each wb In xlApp...

Copy sheet from excel workbook to another workbook

Below is my code for the copying process from one workbook to another.
I looked up a lot of similar issues but i could not get this working.
when I run this the two files open up and then i get a third one called book1 with all results. then i get an error "Copy method of Worksheet class failed".
What Im trying to do is copy the general report sheet from o.Book to xBook.
I want to leave the books open for now until this is correct but i will use Xbook later.
Can I get help with this please?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oExcel As Excel.ApplicationClass
Dim oBook As Excel.WorkbookClass
Dim oBooks As Excel.Workbooks
Dim xExcel As Excel.ApplicationClass
Dim xBook As Excel.WorkbookClass
Dim xBooks As Excel.Workbooks
Dim user As String
Dim opath As String
Dim opathS As String
Dim timeStamp As DateTime = DateTime.Now
Dim path2 As String
Label1.Text = "Working..."
'Get the current system user user and set path to file
user = Environment.UserName
opath = "C:\Users\" + user + "\Downloads\ADC Open.xls"
path2 = "C:\Users\" + user + "\Downloads\Personal.xlsm"
opathS = "C:\Users\" + user + "\Desktop\Report.xls"
'Create first object
oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False
oExcel.Visible = True
oBooks = oExcel.Workbooks
'Create second object
xExcel = CreateObject("Excel.Application")
xExcel.DisplayAlerts = False
xExcel.Visible = True
xBooks = xExcel.Workbooks
'open first book
oBook = oBooks.Open(opath)
'open second book
xBook = xBooks.Open(path2)
oBook.Worksheets("general_report").Copy(After:=xBook.Worksheets("general_report"))
'Run the subroutine.
'xExcel.Run("Execute")
'xExcel.DisplayAlerts = False
'Delete sheet not needed any more
'xBook.Sheets("general_report").Delete
'xExcel.DisplayAlerts = False
'Save results to new file
xBook.SaveAs(opathS)
Label1.Text = "File saved at: " + opathS
'Close the workbook and quit Excel.
oBook.Close(False)
System.Runtime.InteropServices.Marshal.
ReleaseComObject(oBook)
oBook = Nothing
System.Runtime.InteropServices.Marshal.
ReleaseComObject(oBooks)
oBooks = Nothing
oExcel.Quit()
System.Runtime.InteropServices.Marshal.
ReleaseComObject(oExcel)
oExcel = Nothing
'Delete original file after finished with it
'System.IO.File.Delete(opath)
End Sub
Can't add a comment yet, but if VB is the same across all platforms, shouldn't you Set the variable after declaring it ?
Set MyObject = YourObject ' Assign object reference.
Set MyObject = Nothing ' Discontinue association.
After all the responses I started looking into these object settings and find code that help with the explainations, I refactored my previous version and this is what I came up with. It works like a charm now. Thanks everyone for the help and comments.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application = New Excel.Application
Dim user As String
Dim sourcePath As String
Dim targetPath As String
Dim savePath As String
Label1.Text = "Working..."
user = Environment.UserName
sourcePath = "C:\Users\" + user + "\Desktop\Report\ADC Open (Dell GTIE JIRA).xls"
targetPath = "C:\Users\" + user + "\Desktop\Report\Personal1.xlsm"
savePath = "C:\Users\" + user + "\Desktop\Report\Report" & Format(Now(), "DD-MMM-YYYY") & ".xlsm"
Dim wbSourceBook As Excel.Workbook = xlApp.Workbooks.Open _
(sourcePath, ReadOnly:=False)
Dim wbTargetBook As Excel.Workbook = xlApp.Workbooks.Open _
(targetPath, ReadOnly:=False)
'Excel expects to receive an array of objects that
'represent the worksheets to be copied or moved.
Dim oSheetsList() As Object = {"general_report"}
wbSourceBook.Sheets(oSheetsList).Copy(Before:=wbTargetBook.Worksheets(1))
wbSourceBook.Close(True)

How can I save a new sheet into an exsisting workbook from datagridview using visual studio

I am exporting my data from visual studio data grid view into excel and I want to know how to add/save new sheets into an existing excel file.
If using OleDb the use SQL to create a sheet
Public Module Demo
Public Sub DemoOleDbCreateXls_WithHeaders()
Using cn As New OleDb.OleDbConnection With {.ConnectionString = "Your connection string"}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText = "CREATE TABLE Members(FirstName CHAR(255),LastName CHAR(255),JoinedYear INT)"
cn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO Members (FirstName,LastName,JoinedYear) VALUES ('Kevin','Gallagher',2013)"
cmd.ExecuteNonQuery()
cmd.CommandText = "CREATE TABLE Officiers(FirstName CHAR(255),LastName CHAR(255),Rank CHAR(255))"
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO Officiers (FirstName,LastName,Rank) VALUES ('Joan','Gallagher','AAA')"
cmd.ExecuteNonQuery()
cmd.CommandText = "CREATE TABLE Test1(Description CHAR(255),Amount Double)"
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO Test1 (Description,Amount) VALUES ('Dues',12.99)"
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
End Module
Using Excel automation
Option Strict On
Option Infer Off
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Module Demo
Public Sub CreateSheetIfNeeded(ByVal FileName As String, ByVal SheetName As String)
If IO.File.Exists(FileName) Then
Dim Proceed As Boolean = False
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
'
' For/Next finds our sheet
'
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Proceed = True
Exit For
End If
Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
Dim workSheet As Excel.Worksheet = Nothing
Dim xlNewSheet As Excel.Worksheet = Nothing
If Proceed Then
' do work, sheet exists
Else
workSheet = CType(xlWorkSheets(1), Excel.Worksheet)
xlNewSheet = DirectCast(xlWorkSheets.Add(workSheet), Excel.Worksheet)
xlNewSheet.Name = SheetName
End If
xlWorkBook.SaveAs(FileName)
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseExcelObject(xlNewSheet)
ReleaseExcelObject(workSheet)
ReleaseExcelObject(xlWorkSheets)
ReleaseExcelObject(xlWorkSheet)
ReleaseExcelObject(xlWorkBook)
ReleaseExcelObject(xlWorkBooks)
ReleaseExcelObject(xlApp)
Else
' file does not exists
End If
End Sub
Private Sub ReleaseExcelObject(ByVal excelObject As Object)
Try
If excelObject IsNot Nothing Then
Marshal.ReleaseComObject(excelObject)
excelObject = Nothing
End If
Catch ex As Exception
excelObject = Nothing
End Try
End Sub
End Module

Visual basic with excel automation

I have been unsuccessful in setting the row height and column widths of an excel spreadsheet from within a visual basic application.
I have a visual basic application where I have data in my clipboard. I copy that code to an instance of excel and then have excel save the resulting spreadsheet and then excel closes. I am trying to programmatically set the row heights and cell widths prior to saving the spreadsheet but have been unable to do so. This is the code that I am executing:
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
oXL = CreateObject("Excel.Application")
oXL.Visible = True
oWB = oXL.Workbooks.Add
oSheet = oWB.ActiveSheet
oSheet.Paste()
oSheet.Cells.Select()
oSheet.Selection.RowHeight = 11.4
oSheet.Cells.EntireColumn.AutoFit()
oSheet = Nothing
oWB.Close(True, SaveFileDialog1.FileName)
oWB = Nothing
oXL.Quit()
oXL = Nothing
MsgBox("Finished!")
End If
The application runs without the oSheet.Cells.Select(), oSheet.Selection.RowHeight = 11.4, and oSheet.Cells.EntireColumn.AutoFit()
lines. With these lines, I get this error dialog message:
Public member 'Selection' on type 'Worksheet' not found.
When I trace the program in Visual Studio, the oSheet.Paste() command executes and the oSheet.Cells.Select() command executes. The exception is generated when I try to execute the oSheet.Selection.RowHeight = 11.4 command.
Any assistance would be greatly appreciated.
Jonathan
The following is not late binding, it's early binding but the pattern should work with minor code changes.
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Imports System.IO
Public Class Operations
Public HasError As Boolean
Public ErrorMessage As String
''' <summary>
'''
''' </summary>
''' <param name="FileName">Path and file name for Excel file</param>
''' <param name="SheetName">Sheet name to work on</param>
''' <param name="RowHeight">Used to set row height in SheetName</param>
''' <returns></returns>
Public Function SetWidthHeight(
ByVal FileName As String,
ByVal SheetName As String,
ByVal RowHeight As Integer) As Boolean
If File.Exists(FileName) Then
Dim Proceed As Boolean = False
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
Dim xlCells As Excel.Range = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Proceed = True
Exit For
End If
Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
If Proceed Then
xlCells = xlWorkSheet.Cells
xlCells.PasteSpecial()
Dim EntireRow As Excel.Range = xlCells.EntireRow
'
' Set row height
'
EntireRow.RowHeight = RowHeight
Dim ColRange = xlCells.EntireColumn
'
' Auto fit all columns
'
ColRange.AutoFit()
ReleaseComObject(ColRange)
ReleaseComObject(xlCells)
ReleaseComObject(EntireRow)
Else
HasError = True
ErrorMessage = SheetName & " not found."
End If
xlWorkSheet.SaveAs(FileName)
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
Else
HasError = True
ErrorMessage = "'" & FileName &
"' not located. Try one of the write examples first."
End If
Return HasError
End Function
Private Sub ReleaseComObject(ByVal excelObject As Object)
Try
If excelObject IsNot Nothing Then
Marshal.ReleaseComObject(excelObject)
excelObject = Nothing
End If
Catch ex As Exception
excelObject = Nothing
End Try
End Sub
End Class

Start empty Excel workbook without any worksheets

Creating a new Excel workbook as in:
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Set xl = New Excel.Application
xl.Visible = False
Set wb = xl.Workbooks.Add
Is there an easy way to stop Excel automatically creating Sheet1, Sheet2, Sheet3?
I can always delete these unwanted sheets afterwards but that feels like a clunky solution.
xl.SheetsInNewWorkbook = 1
More Information on MSDN (Scroll down to Add method as it applies to the Workbooks object.)
Full Code:
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Dim restoreSheetsInNewWorkbook As Long
Set xl = New Excel.Application
restoreSheetsInNewWorkbook = xl.SheetsInNewWorkbook
xl.SheetsInNewWorkbook = 1
Set wb = xl.Workbooks.Add
xl.SheetsInNewWorkbook = restoreSheetsInNewWorkbook 'or just set it to 3'
Or you can:
Excel 2003
Tools>Options>General Tab and change the "Sheets in new workbook" to 1
Excel 2007
Office Button>Excel Options>Popular Section>When creating new workbooks...>Include this many sheets>1
Can't create one without any sheets (to the best of my knowledge), but you can create a workbook with a single sheet without messing around with the user's settings.
dim wb as Workbook
Set wb = xl.Workbooks.Add(xlWBATWorksheet)
Sub DeleteSheets()
Dim DeleteSheet As Variant
Dim ws As Worksheet
DeleteSheet = Array("Sheet1", "Sheet2", "Sheet3")
Application.DisplayAlerts = False
For Each ws In Worksheets
If IsInArray(ws.Name, DeleteSheet) Then ws.Delete
Next
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
Dim i As Integer
Dim Ret As Boolean
Ret = False
For i = LBound(arr) To UBound(arr)
If VBA.UCase(stringToBeFound) = VBA.UCase(arr(i)) Then
Ret = True
Exit For
End If
Next i
IsInArray = Ret
End Function

Resources