Excel Object generates error after the application is published - vb.net

My VB.NET Windows forms application is writing data into excel file. It works without any error in development environment. The excel file gets created with data.
But when the application is deployed/Published. It gives error : "Object reference not set to an instance of an object" at xlWorkBook.SaveAs
Error is confusing. Is it a permission issue? Any help.
Below is the code:
Dim xlApp As Excel.Application = New Excel.Application
xlApp.SheetsInNewWorkbook = 1
Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add
Dim xlWorkSheet As Excel.Worksheet = CType(xlWorkBook.Worksheets.Add(), Excel.Worksheet)
xlWorkSheet.Name = "Sample1"
xlWorkSheet.Cells(1, 1) = "TestData1"
xlWorkSheet.Cells(1, 2) = "TestData2"
xlApp.DisplayAlerts = False
xlWorkBook.SaveAs(gExcelFileName, Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges)

The solution I found for this issue is to change the folder location in the variable "gExcelFileName" to a local folder on the machine where it is installed. It works now. I think it is a permission issue.

Did you publish your application with excel interop dll? different version of excel may have different parameter, if you don't want to publish your application with excel dll, try to use named parameter:
xlWorkBook.SaveAs(FileName:=gExcelFileName,
FileFormat:=Excel.XlFileFormat.xlWorkbookDefault,
AccessMode:=Excel.XlSaveAsAccessMode.xlNoChange,
ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges)

Related

vb.net & office: Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass'

I'm developing a vb.net application and it should open and handle a excel file.
The problem is that in my pc (and the same could happen in other pc where it could be installed) I have Visio version 2013 and Office (excel, word, etc..) version 2010. Integrating excel in vb is so simple because more or less automatic, done in few steps.. but in the same time so stupid: calling interop.Excel functions, it addresses to the newest version of office intalled (2013), but I don't have excel for that version!
I searched a lot on the web about this issue, and every where I found the solution of deleting a registry key, well, it works fine, but every time I use Visio, it seems the registry key is recreated again.
My questions are:
can I select which version of excel I would like to link my application?
I can understand that fixing the version I should handle any office versions
manually.. but maybe I prefer doing this..
can I copy a dll in the application folder to be sure that the app uses that
version? I tried with Microsoft.Office.Interop.Excel.dll and Office.dll but still the issue
I don't want to follow the way of deleting the registry key programmatically, is not safe in my opinion..
I can't believe that the integration between office and .net is so stupid that is not able to use the right version of excel installed!!
;-P
Code:
Dim fileTest As String = FilePath
Dim APP As New Application
MsgBox(APP.Version)
Dim oSheet As Excel.Worksheet = Nothing
Dim workbook As Excel.Workbook = Nothing
Dim IndexFound As Integer = 0
Dim StartRow As Integer = 10
Dim DateSelected As String = ""
Dim resultOK As Boolean = False
Try
workbook = APP.Workbooks.Open(fileTest)
oSheet = workbook.Worksheets("Activities")
APP.DisplayAlerts = False
oSheet.Range("A2").Value = "test"
oSheet.Range("B3").Value = "Ciao"
Catch ex As Exception
MsgBox("Error: " + ex.Message)
If Not resultOK Then
If Not workbook Is Nothing Then
workbook.Close()
While System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook) > 0
End While
workbook = Nothing
End If
oSheet = Nothing
workbook = Nothing
APP.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(APP)
APP = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
End If
End Try
End Sub
Thanks
Andrea

Class not registered Exception

In my web site project I need to create an excel file in Server site. Thus I uese the following.
Try
Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()
If xlApp Is Nothing Then
srvHandler.ErrorAnswer = "Excel is not properly installed!!\r\n CreateExcel xlApp"
ServerHandler._InnerError += srvHandler.ErrorAnswer
_Default.errorCall = True
Return
End If
'Dim xlWorkBooks As Excel.Workbooks = xlApp.Workbooks
Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet)
Dim xlWorkSheet As Excel.Sheets = xlWorkBook.Worksheets
Dim misValue As Object = System.Reflection.Missing.Value
xlWorkSheet.Item(1).Name = "Page1"
If xlWorkSheet Is Nothing Then
srvHandler.ErrorAnswer = "ERROR: xlWorkSheet == null!!\r\n CreateExcel xlWorkSheet"
ServerHandler._InnerError += srvHandler.ErrorAnswer
_Default.errorCall = True
End If
The all code it runs excellent in my PC but when I send it to my ISP it produces the problem
At the point of
Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()
It throws me the following error
Create Excel Retrieving the COM class factory for component with CLSID
{00024500-0000-C000-000000000046} failed due to the following error:
80040154 Class not registered Exception
I try few ways to overcome but was worthless
Is there someone to assist me on this?
I don't think they have Excel installed.
Or if they have during install you have to enable .NET support (at least you had to do it in Office 2003 if I remember correctly).

Getting the users save as path from excel.application after giving them control

How can I get the saved file path from an Excel.Application object after showing the object and giving the user control?
I don't know that it's important, but I need this information because I want to write this path to registry so the app knows where to go for searching or future editing. If the file does not exist or my program has no location provided, then I want to start creating one with the default headings and allow them to edit and save as with excel.
The main function of the program is to read the excel file for search values and populate form controls. This feature is file maintenance / error handling.
My current code:
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim misVal As Object = Reflection.Missing.Value
Here I tried to make the user save the file somewhere before editing, but excel still asks them to save as when closing.
xlApp = New Excel.Application
Dim file As String = xlApp.GetSaveAsFilename()
xlApp = New Excel.Application(file)
Showing the workbook works fine, I'm just stuck on how to retrieve the path the user saved to after they close the showing interface.
xlBook = xlApp.Workbooks.Add(misVal)
xlSheet = xlBook.Sheets("sheet1")
xlSheet.Cells(1, 1) = "Group #"
xlApp.DefaultSaveFormat = Excel.XlFileFormat.xlExcel12
xlApp.UserControl = True
xlApp.Visible = True
Thanks, Boom
EDIT:
Henderso's answer is basically what I ended up doing.
xlApp = New Excel.Application
Dim file As String = xlApp.GetSaveAsFilename()
' make changes to the book
xlBook.SaveAs(file)
xlApp = New Excel.Application(file)
After this I kept getting the prompt from excel to save as when the user closed the window. using xlBook.Saved = True fixed this. I wanted the user to select a location for the file to be and then have the program "auto save" when closing so I needed to also add an event handler
AddHandler xlBook.BeforeClose, AddressOf auto_save
where auto_save is the name of a sub I defined to do the work of the handler xlBook.save().
This code will create a new book, and prompt for new file name. To the user, they will first get the save as prompt, then the new WB is shown. Flname contains the full path of the save as file:
Set NewWkbk = Workbooks.Add
Flname = Application.GetSaveAsFilename(InitialFileName:="", FileFilter:="Excel Files (*.xlsx), *.xlsx", Title:="Enter Path for new file..")
NewWkbk.SaveAs (Flname)
Note, the GetSaveAsFilename filter is specifying .xlsx filetype. You may need to adjust this is you want .xls or .xlsm

Open Excel File issue

I'm getting the error:
Microsoft Excel cannot access the file '..\services\Calculator.xlsx'.
There are several possible reasons: • The file name or path does not
exist. • The file is being used by another program. • The workbook you
are trying to save has the same name as a currently open workbook.
Any ideas?
I tried this, but does not seem to work Microsoft Office Excel cannot access the file 'c:\inetpub\wwwroot\Timesheet\App_Data\Template.xlsx'
Dim xlApp As Application = New Application
Dim xlWB As Workbook
xlWB = xlApp.Workbooks.Open(Server.MapPath("~") + "\services\Calculator.xlsx", 2, True)
Dim xlSheet As Worksheet = xlWB.Sheets("input output")
xlSheet.Cells(7, 8).value = drpTrades.SelectedValue
xlSheet.Cells(12, 8).value = Convert.ToDecimal(txtIncome.Text)
xlSheet.Cells(9, 8).value = loan.Text
Dim xlRebate As Decimal = xlSheet.Cells(18, 8).value
If xlRebate < 0 Then lblRebate.ForeColor = System.Drawing.Color.Red
lblRebate.Text = "£" + Math.Round(xlRebate, 2).ToString
xlWB.Close(False)
xlApp.Quit()
ReleaseComObject(xlApp)
xlApp = Nothing
I found the solution that worked for me.
If you open up Component Services (Located under Control Panel >Admin Tools)
Computers >My Computer>DCom Config>Microsoft Excel Application, properties, Identity tab, select user.
I created a new new local account to run it under and it all worked.

Open Excel file in VBA from Powerpoint

I'm trying to open the Excel file using VBA in Powerpoint 2010 with the help of following code.
Private Sub CommandButton1_Click()
Dim xlApp As Excel.Application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Workbooks.Open "C:\lol\Book1.xlsx", True, False
Set xlApp = Nothing
Range("A8").Value = "Hello"
End
But I'm getting the following error.
Compile Error
User Defined type not defined.
Am I missing something. Can anyone share the sample piece of code to open an excel file, change a cell value and close Excel file in Powerpoint 2007 and 2010 using VBA.
I have searched a lot and tried different pieces of code, but getting the same error everytime. :(
Thanks in advance. :)
Have you added a reference to the Excel Object Model? That would save you having to use the late bound objects (and you get the benefit of having the Intellisense help when you are coding).
You need to go to Tools -> References and check the "Microsoft Excel v.x Object Library" (I think that number changes depending on the version of office you are using.
Your code should work if you do that, you should also remove the
CreateObject("Excel.Application")
line and replace it with
Set xlApp = new Excel.Application
And move the
Set xlApp = nothing
line to the end of your subroutine.
The rest of your code looks fine to me.
Late binding code would be this
Private Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkbook = xlApp.Workbooks.Open("C:\lol\Book1.xlsx", True, False)
xlWorkbook.sheets(1).Range("A8").Value = "Hello"
Set xlApp = Nothing
Set xlWorkbook = Nothing
End Sub
It's better to use early binding though.