VB.Net Interop Excel Com Exception - vb.net

This code was working perfect for quite a while till now,
It throws exception :
System.InvalidCastException: Unable to cast COM object of type
'System.__ComObject' to class type
'Microsoft.Office.Interop.Excel.WorksheetClass'
Dim ds_allJobs As DataSet = DBHandling.searchJob("", "", "all open jobs")
Dim xlApp = New Microsoft.Office.Interop.Excel.Application
xlApp.Visible = False
xlApp.ScreenUpdating = False
Dim xlWorkbook = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
Dim xlWorksheet = New Microsoft.Office.Interop.Excel.Worksheet
xlWorksheet = xlWorkbook.ActiveSheet 'IT FAILS HERE
xlWorksheet.Name = "Open Jobs"
Any suggestions?

It is better if you specify the types of objects (e.g. exWorkbook As Excel.Workbook)
Here is a way to make a new worksheet:
'create a new excel application (window)
Dim exApp As New Excel.Application
'add a workbook to it, and take a look at the first worksheet
Dim exWorkbook As Excel.Workbook = exApp.Application.Workbooks.Add()
'create a new worksheet
Dim exWorksheet As Excel.Worksheet
'add this worksheet to the current applicatoin
exWorksheet = CType(exApp.Worksheets.Add(), Excel.Worksheet)
Doe this answer your question? The last line is Casting the object to type worksheet.

Related

Excel.Worksheet.Columns(1).NumberFormat = "#" Late Binding Warning

I'm getting a late binding warning on the below code, specifically the last line.
Dim xlApp As New Excel.Application
Dim xlWorkbook As Excel.Workbook = xlApp.Workbooks.Add()
Dim xlSheet As Excel.Worksheet = CType(xlWorkbook .Sheets(1), Excel.Worksheet)
xlSheet.Name = "Summary"
xlSheet.Columns(5).NumberFormat = "#"
I'm not getting the error on the .Name property line so presumably it's an issue with .Columns?
Why is this?
Try removing the New keyword in
Dim xlApp as New Excel.Application

Write in an already opened Excel workbook from Powerpoint Slide

I am trying to write in an already manually opened workbook using VBA from my PowerPoint presentation.
Using CreateObject and then Workbook.Open it opens a new instance of the file.
I'm trying to use GetObject as found in several examples over the web.
Here's my code :
Dim xlApp As Object
Dim xlWorkbook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = Trueme
Set xlWorkbook = xlApp.Workbooks.Open(ActivePresentation.Path & "\Suivi individuel.xlsx", True, False)
xlWorkbook.Sheets(1).Range("C14").Value = "Hello"
SlideShowWindows(1).View.GotoSlide nextSlide
I've tried:
Dim xlApp As Object
Dim xlWorkbook As Object
Set xlWorkbook = GetObject(ActivePresentation.Path & "\Suivi individuel.xlsx", "Excel.Application")
xlWorkbook.Sheets(1).Range("C14").Value = "Hello"
SlideShowWindows(1).View.GotoSlide nextSlide
It says runtime error 432: File Name or Class Name not found during automation operation.
Try:
Dim xlApp As Object
Dim xlWorkbook As Object
Set xlWorkbook = GetObject(ActivePresentation.Path & "\Suivi individuel.xlsx")
If you just want to get an open instance of Excel then
Set xlApp = GetObject(,"Excel.Application")
Set xlWorkbook = xlApp.ActiveWorkbook
Wrap that in an error handler if there's a chance Excel might not be open
See: https://support.microsoft.com/en-us/kb/288902

Creating Excel Files using VB2010

I have a form with 1 button to create an Excel file on my desktop.
I get error message:
NullReferenceException Was Unhandled
Object reference not set to an instance of an object
and it highlights the code:
WB = excelapp.workbooks.add
I did add the reference "Microsoft excel 14.0" and my full code is below:
imports excel = microsoft.office.interop.excel
dim excelapp as excel.application
dim WB as excel.workbook
sub button1()
WB = excelapp.workbooks.add
excelapp.visible=true
end sub
Missing New on your Excel instance for starters:
Dim xlApp As New Excel.Application
Dim xlWorkbook As Excel.Workbook = xlApp.Workbooks.Add()
Dim xlWorksheet As Excel.Worksheet = CType(xlWorkbook.Sheets("sheet1"), Excel.Worksheet)
xlWorksheet.Cells(1, 1) = "data in first cell"
xlWorksheet.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & "Test.xlsx")
xlWorkbook.Close()
xlApp.Quit()
xlApp = Nothing
xlWorkBook = Nothing
xlWorkSheet = Nothing
You should probably put this in Try/Catch/Finally block to catch errors in case you run into issues, but mostly because if the program doesn't continue properly finish that code block, an EXCEL.EXE will remain open in your task manager, as well as whatever Excel file it was accessing will be "in use by another program" when you try to access/modify/delete it.
just add one line, then it'll work
imports excel = microsoft.office.interop.excel
dim excelapp as excel.application
dim WB as excel.workbook
sub button1()
excelapp = new excel.application
WB = excelapp.workbooks.add
excelapp.visible=true
end sub

Getting TXT file to Excel

I have the following code to get a text file to an Excel workbook.
Dim XlApp As Excel.Application = New Excel.Application
Dim XlWbk As Excel.Workbook = XlApp.Workbooks.Add
Dim SheetName As String = "Sheet1"
Dim XlWkst As Excel.Worksheet = FindSheet(XlWbk, SheetName)
Dim XlRng As Excel.Range = Nothing
If XlWkst Is Nothing Then
XlWkst = DirectCast(XlWbk.Sheets.Add(After:=XlWbk.Sheets(XlWbk.Sheets.Count), _
Count:=1, Type:=Excel.XlSheetType.xlWorksheet), Excel.Worksheet)
End If
Dim Lines() As String = File.ReadAllLines("C:\TEMP\FlowgateNNL_Mar2011_base.txt")
Dim RC(Lines.Length - 1)() As String
For I As Integer = 0 To Lines.Length - 1
RC(I) = Lines(I).Split(CChar(vbTab))
Next
XlRng = XlWkst.Range("a1")
XlRng.Value = RC
XlApp.Visible = True
This method seems to be the fastest way to read and parse a CSV file for dumping to Excel on my computer. it is choking on XlRng.Value = RC. Excel doesn't seem to like RC.
Any ideas for getting Excel to accept the data?
You are setting the value of a cell to an array that contains an entire CSV? I'm guessing this throws a type error.
This is probably more along the lines of what you want.
Dim XlApp As Excel.Application = New Excel.Application
Dim XlWbk As Excel.Workbook = XlApp.Workbooks.Add
Dim SheetName As String = "Sheet1"
Dim XlWkst As Excel.Worksheet = FindSheet(XlWbk, SheetName)
Dim XlRng As Excel.Range = Nothing
If XlWkst Is Nothing Then
XlWkst = DirectCast(XlWbk.Sheets.Add(After:=XlWbk.Sheets(XlWbk.Sheets.Count), _
Count:=1, Type:=Excel.XlSheetType.xlWorksheet), Excel.Worksheet)
End If
Dim Lines() As String = File.ReadAllLines("C:\TEMP\FlowgateNNL_Mar2011_base.txt")
For I As Integer = 0 To Lines.Length - 1
XlRng = XlWkst.Range("a1").Offset(I, 0)
Dim RC() As String = Lines(I).Split(CChar(vbTab))
For J As Integer = 0 To RC.Length - 1
XlRng = XlRng.Offset(0, J)
XlRng.Value = RC(J)
Next
Next
XlApp.Visible = True
Did you try simply opening the CSV file directly as in:
Dim XlApp As Excel.Application = New Excel.Application
Dim XlWbk As Excel.Workbook = XlApp.Workbooks.Open("C:\TEMP\FlowgateNNL_Mar2011_base.txt")
XlApp.Visible = True
If you have a valid CSV file do yourself a favor and use a specialised CSV datareader which can handle all the weird problems of CSVs (quotes etc.)
Personally, I like http://kbcsv.codeplex.com/ very much - it is simple to use and fast.
Then just dump the interop part and use the EPPLUS Library to write the data to an excel file - it is magnitudes faster and mind boggingly simple.
Your workflow would look like this:
Use KBCSV to load the data to a datatable.
Use EPPLUS's method "LoadFromDataTable" to generate a new excel file and save it.
Done!

Modifying a template based excel in VB.NET

I am tyring to run code like this
xlWorkSheet.Cells(rownumber, 1) = "Some Value"
the problem is when I open the excel document the cell value is not updated.
any help will be appreciated
I use the following code to open the file
Dim pathtofile As String = Server.MapPath("~/UserControls/Upload/MyUpload.xlsx")
Dim xlApp As Excel.Application =New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlworkbooks As Excel.Workbooks
Dim xlWorksheets As Excel.Worksheets
Dim misValue As Object = System.Reflection.Missing.Value
Dim xlWorkSheet As Excel.Worksheet = Nothing
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlworkbooks = xlApp.Workbooks
xlWorkBook = xlworkbooks.Open(pathtofile )
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
You need to save, close, and release the com objects to make sure excel doesn't remain running as a process.
Sub save(filename As String) ' Saves the sheet under a specfic name
xlWorkBook.SaveAs(filename)
End Sub
Sub closexl()
xlWorkBooks.Close()
xlApp.Quit()
End Sub
Sub cleanup() ' Releases all of the com objects to object not have excel running as a process after this method finishes
GC.Collect()
GC.WaitForPendingFinalizers()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
xlApp = Nothing
End Sub