Open Excel File issue - vb.net

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.

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

Using excel as inputfile in vba (scripting - non MS OFFICE)

I'm developing a script in VBA (inside a workspace, not MS office program) that needs to use a small excel file as input. I want to use the data in the excel file and load it into a 2D array so that I can make decisions within my script based on this data.
I've tried to google this problem but generally I find problems within excel, but I haven't had any luck finding anything for vba scripting outside MS office.
Can I just use a .Xlsx as inputfile?
How do I put this data into a 2d array? My file only has 11 rows & 2 columns.
Thank you for your time.
This is confusing. VBA = MS Office VBA, as far as I know. Do you mean VB.NET? VBS? Anyway, to extract data from an xlsx file without opening it in Excel, you either need to unzip it and dig through the XML files inside, or use Office Open XML SDK or any other package like that.
Open XML SDK
Office Open XML fileformat
I think this will also work for Visual Basic [for Applications]; I tried it in Excel VBA and Word VBA:
In VBA Development Environment, select Tools, References. In the list that now appears, check the Object Model you need. In your case you will want to check the Microsoft Excel 12.0 Object Library.
You now have access to the complete Excel Object Model in your application and can open and manipulate an Excel spreadsheet file as you need.
The following code in VB for Word opens an Excel Spreadsheet and gets the value of the first cell:
Sub ExcelTestInWord()
Dim oExcel As Object
Dim wb As Object
Dim v
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
Dim vrtSelectedItem As Variant
Set oExcel = CreateObject("Excel.Application")
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
If (fd.Show = -1) Then
For Each vrtSelectedItem In fd.SelectedItems
Set wb = oExcel.Workbooks.Open(vrtSelectedItem)
v = wb.Sheets(1).Cells(1).Value
wb.Close
Next vrtSelectedItem
End If
End Sub
Consider the VBScript code below as an example, save it as .vbs file to launch:
Option Explicit
Dim strSourceFilePath, strSourceSheetName, strSourceRange, arrData, strResult, i, j
' set initial data
strSourceFilePath = "C:\Test\data.xlsx"
strSourceSheetName = "input"
strSourceRange = "A1:B11"
' get 2-dimensional array from Excel sheet
With CreateObject("Excel.Application")
.Visible = False
.DisplayAlerts = False
With .Workbooks.Open(strSourceFilePath)
arrData = .Sheets(strSourceSheetName).Range(strSourceRange).Value
.Close
End With
.Quit
End With
' array output for debug purposes
strResult = ""
For j = 1 To UBound(arrData, 1)
For i = 1 To UBound(arrData, 2)
strResult = strResult & arrData(j, i) & ";" & vbTab
Next
strResult = strResult & vbCrLf
Next
WScript.Echo strResult

Excel Object generates error after the application is published

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)

Opening and Excel file in Access using VBA and saving it to a different name and closing it properly

I have been searching for some time on how exactly to go about this, but I keep coming up with a large number of possible ways that come close, but never really give me exactly the sort of thing I'm looking for. The concept is pretty simple I need to open a certian .xls file using some VBA code in Access 2010. Once the file is opened I need to insert data and do some things to the file then save the file as a different filename and close the file. I also need it to close excel if it was not already open and if it was open I need it to leave excel alone and not save/close anything other than the template.xls file I am working with. I currently have code that will do part of this provided Excel is not already open at the time the script runs. When excel is already opened I get the following error;
"Run-time'91': Object variable or With block variable not set."
When I click debug I get the following line highlighted
x.ActiveWorkbook.SaveAs fileName:=savedfilename
Here is the code without all the junk that doesn't relate to the issue. I have cobbled together using examples from various sites.
Dim DateSampled As String
Dim strPath As String
Dim TemplatePath As String
Dim x As Excel.Application
Dim xBook As Excel.Workbook
Dim xSheet As Excel.Worksheet
DateAsString = Format(DateSampled, "MMDDYYYY")
savedfilename = strPath & "\" & TrainNum & "-" & DateAsString & ".xls"
TemplatePath = "B:\template.xls"
Set x = CreateObject("Excel.Application")
x.Visible = False
Set xBook = GetObject(TemplatePath)
xBook.Windows(1).Visible = True
Set xSheet = xBook.Worksheets(1)
'---------------CODE DOES STUFF WITH THE FILE -----------------------
x.DisplayAlerts = False
x.ActiveWorkbook.SaveAs fileName:=savedfilename
x.DisplayAlerts = True
x.ActiveWorkbook.Close
Set x = Nothing
Set xBook = Nothing
Set xSheet = Nothing

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