Opening a dynamically created Excel workbook - excel

I have a Windows Forms app with an Excel file I created using SpreadsheetGear. My application uses SaveFileDialog() to prompt the user to save the file to their computer using the following code:
'Bring up the save dialog to save the newly created Excel file
Using saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.FileName = "ExportFile.xlsx"
If DialogResult.OK <> saveFileDialog1.ShowDialog() Then
Return
End If
Try
e.Result.SaveAs(saveFileDialog1.FileName, FileFormat.OpenXMLWorkbook)
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message, "Save Error", MessageBoxButtons.OK)
End Try
End Using
That code works fine but the user doesn't want to worry about saving the file. He just wants it to open right away so he can copy/paste the information he needs and then discard the file without having to navigate to his save destination. I can't seem to get SaveFileDialog() to do that for me.
Is there a better way to do this?

This closed question helped me discover my answer. Process.Start with the filename from the SaveFileDialog works.
Updated Code:
'Bring up the save dialog to save the newly created Excel file
Using saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.FileName = "ExportFile.xlsx"
If DialogResult.OK <> saveFileDialog1.ShowDialog() Then
Return
End If
Try
e.Result.SaveAs(saveFileDialog1.FileName, FileFormat.OpenXMLWorkbook)
If File.Exists(saveFileDialog1.FileName) Then
Process.Start(saveFileDialog1.FileName) 'Open the newly created Excel file
Else
Throw New Exception("Could not find file to open. Please try again.")
End If
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message, "Save Error", MessageBoxButtons.OK)
End Try
End Using

Related

VBA Can't save Access Form via Excel

I tried to connect my Excel to Access via VBA. And I managed to connect to my Access Form
but when I try to save it, it doesn't work.
...
Set conn = CreateObject("Access.Application")
conn.OpenCurrentDatabase conPath
On Error GoTo ende
conn.DoCmd.OpenForm "frm_test", acFormDS, "", "", , acNormal
conn.Forms![frm_test]![Year] = year
conn.Forms![frm_test]![Status] = "open"
conn.DoCmd.OutputTo acOutputForm, "frm_test", acFormatXLS, , True
When I execute the code it opens the explorer window and I can choose where to save the file.
But when I click on save there is no file and no file is open afterwards.
Can someone help me?

VBA OLE Error when tring to new created xlsx file Attachment in Lotus Notes

I am tring to send some new Excle files that i created before.
When i try to send them with Lotus Notes i get an OLE error but when i try to send a test file it works without Problem. Can someone give me a tip where the Problem lies?
This i my Attachment part in the E-Mail function:
stAttachment = EmailAttachment
Set AttachMe = MailDoc.CREATERICHTEXTITEM("stAttachment")
Set EmbedObj = AttachMe.EMBEDOBJECT(1454, "", stAttachment, "stAttachment")
Here i put the targent file:
Filename = "C:\Users\User\Desktop\Excel Notes\test.xlsm"
Filename = "C:\Users\user\Desktop\Excel Notes\generated.xlsm"
EMail.EMailBuild EmailAdress, EmailHeader, EmailText, Filename
when i try the test file it functions but when i set the generatet file i get this error
waiting for another application to complete an OEL action

Integration of SQlite database (or any other suggestion) with Excel project in VB

I am very new to VB. I am working on an Excel-VB(2013) project in which I want to read data from another excel file, then compare some of its fields with existing data. So the question is about existing database which sits inside the application (no server, no online connection).
I was wondering how can I add a sqlite DB file (or any other) into my project and then connect to that db and use it. I need help with some examples.
Thank you,
You can embed it into any executable file, but you have to extract it to use it, usually in the temp folder. I use Reshacker to embed resources. Here's some old code. I'd use a adodb stream object these days rather than VB file operators.
Sub WriteFiles(DirectoryName, ResourceNo, FileName, FileNumber)
frmSplash.Update FileNumber
DoEvents
Data = LoadResData(ResourceNo, "CUSTOM")
fileNum = FreeFile()
Open DirectoryName & "\" & FileName For Binary As #fileNum
For x = 0 To UBound(Data)
Put #fileNum, , CByte(Data(x))
frmSplash.Label8 = FormatNumber(x / UBound(Data) * 100, 0) & "%"
DoEvents
Next
Close fileNum
End Sub

How do I make an Excel VBA Function that works when I reopen the document?

OK, I've just written a very simple VBA script that goes off and grabs the file size of a file found at a specified location (edit update code from dscarr):
Public Function FileSize(path As String) As Variant
On Error GoTo Err_FileSize:
Dim retVal As Variant
Dim filesys As Object
Dim file As Object
retVal = ""
Set filesys = CreateObject("Scripting.FileSystemObject")
Set file = filesys.GetFile(path)
retVal = file.Size
Exit_FileSize: On Error Resume Next
FileSize = retVal
Exit Function
Err_FileSize: retVal = "Error: " & Err.Description
Resume Exit_FileSize
End Function
If I import this into a new workbook, save the document as a "Excel Macro-Enabled Workbook" alongside an empty file called readme.txt and then put "./readme.txt" in A1 and "=FileSize(A1)" in A2, A2 evaluates properly to the file size of readme.txt, 0 bytes. Great. If I then save the document, close and reopen it, I'm warned that macros are disabled. If I enable them, the content of A2 has changed to #VALUE! and nothing I do will make the function work again. Has anyone seen this before, can anyone point out the mistake that I'm making here?
edit: the issue seems to be caused by me using relative paths. I can't explain why it works for a new workbook, but not once saved and reopened, but using absolute paths solves the problem, which as dscarr identified, was a "File Not Found" issue.
I duplicated your code in an Excel 2007 Macro Enabled workbook and found that it worked just fine with the following caveats
It does not automatically update the value (e.g. run the FileSize function) when you open the workbook. This can be compensated for by adding some code to the Worrkbook_Open event handler that calculates the workbook.
I get the #VALUE error when it cannot find the file that is specified. Indeed, when the file is missing or incorrectly named the line "Set file = filesys.GetFile(path)" throws the error number 53 "File Not Found". In this case the return value is never set because the line of code that sets it is never called. You could try setting a default value of "File Not Found" before actually attempting to retrieve the file size.
In Excel 2010, Go File->Options->Trust Center->Macro Settings and make sure the Enable option button has been selected.

Releasing Excel after using Interop

I've read many post looking for my answer, but all are similar to this:
Reading excel files in vb.net leaves excel process hanging
My problem is that I don't quit the app...
The idea is this:
If a User has Excel Open, if he has the file I'm interested in open... get that Excel instance and do whatever I want to do...
But I don't to close his File after I'm done... I want him to keep working on it, the problem is that when he closes Excel... The process keeps running... and running... and running after the user closes Excel with the X button...
this is how I try to do it
This piece is used to know if he has Excel open, and in the For I check for the file name I'm interested in.
Try
oApp = GetObject(, "Excel.Application")
libroAbierto = True
For Each libro As Microsoft.Office.Interop.Excel.Workbook In oApp.Workbooks
If libro.Name = EquipoASeccionIdSeccion.Text & ".xlsm" Then
Exit Try
End If
Next
libroAbierto = False
Catch ex As Exception
oApp = New Microsoft.Office.Interop.Excel.Application
End Try
here would be my code... if he hasn't Excel open, I create a new instance, open the file and everything else.
My code ends with this:
If Not libroAbierto Then
libroSeccion.Close(SaveChanges:=True)
oApp.Quit()
Else
oApp.UserControl = True
libroSeccion.Save()
End If
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(libroOriginal)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(libroSeccion)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(origen)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(copiada)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oApp)
libroOriginal = Nothing
libroSeccion = Nothing
oApp = Nothing
origen = Nothing
copiada = Nothing
nuevosGuardados = True
So you can see that, if I opened the file, I call oApp.Quit() and everything else and the Excel Process ends after a few seconds (maybe 5 aprox.)
BUT if I mean the user to keep the file open (not calling Quit()), Excel process keeps running after the user closes Excel with the X button.
Is there any way to do what I try to do?? Control a open instance of excel and releasing everything so when the user closes it with the X button, the Excel Process dies normally???
Thanks!!!
It seems to me it would be better to use CreateObject instead of GetObject(, "Excel.Application") (see http://support.microsoft.com/kb/288902/en and http://technet.microsoft.com/en-us/library/ee176980.aspx). Then call of Quit method before calling of FinalReleaseComObject and assigninh Nothing will be have a clear sense.

Resources