VB excel reloadas causes object disconnected from it's clients - excel

I'm using VB to open an excel file and I'm having trouble with encoding. Some characters are displayed as garbage. I discovered that when I open the file with excel then reopen it with utf8 encoding the characters display correctly. In my VB program when I try to use the reloadas method the reload appears to work but receive the error "object disconnected from it's clients" error message.
Is there a way I can avoid using the reloadas and open the file using utf8? If not how can resolve the error I'm getting?
Dim xlWorkbook As Excel.Workbook = xlapp.Workbooks.Open(SaveFN)
xlWorkbook.WebOptions.Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8
xlWorkbook.ReloadAs(Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8)
Dim xlWorkSheet As Excel.Worksheet = xlWorkbook.Worksheets(1) 'error occurs here
thanks.

when I try to use the reloadas method the reload appears to work but
receive the error "object disconnected from it's clients" error
message.
This is because when the Excel reloads the Workbook, the existing Workbook object is destroyed and the reference held by xlWorkbook is no longer valid.
Based on the usage of WebOptions, the file is probably an Html file. However, Excel does not expose an open method that takes a file format argument. This leaves using Application.ActiveWorkBook or Application.WorkBooks collection as the only means to retrieve a reference to retrieve the Workbook.
Dim xlWorkbook As Excel.Workbook = xlapp.Workbooks.Open(SaveFN)
xlWorkbook.WebOptions.Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8
xlWorkbook.ReloadAs(Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8)
xlWorkbook = xlapp.ActiveWorkbook ' *** add this statement
Dim xlWorkSheet As Excel.Worksheet = xlWorkbook.Worksheets(1)

Related

Opening Excel file with PowerPoint VBA, Inconsistent Results

I have a PowerPoint macro that should open an Excel file.
Public Sub SortList()
Dim MyFile as String
Dim xlApp as Object
Dim xlWorkBook as Object
Set xlApp = CreateObject("Excel.Application")
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
MyFile = SelectedItems(1)
End With
xlApp.Visible = True
xlApp.Workbooks.Open MyFile
Set xlWorkBook = xlApp.Workbooks.Open(MyFile)
This code was previously working with no errors. However, I have started receiving the error message
"Run-time error '-2147467259 (80004005)': Method 'Open' of object 'Workbooks' failed."
The error occurs when trying to run the "Set" line of code.
The issue is that I can see that the code is successfully opening the Excel file!
Things I have tried (in about every possible combination):
-Changing the code to this (I thought maybe the program was trying to open the file twice):
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open(MyFile)
-Adding ReadOnly:= True to both or either .Open command, at one point this gave me an "Automation error- unspecified error" message which I have never seen before...
-Changing the Set line to this (and variations thereof):
xlApp.Workbooks.Open MyFile
Set xlWorkBook = xlApp.Workbooks(Dir(MyFile))
-Ensuring Excel is completely closed prior to running the code
The frustrating aspect is that this code worked perfectly last week, so I'm also at a loss as to why it would suddenly stop working. Any assistance would be greatly appreciated.
Workbooks.Open can cause issues if you call it on an already open workbook.
So, don't open twice. Remove the following line:
xlApp.Workbooks.Open MyFile

VBA: Opening a PowerPoint Presentation from Excel: Error "Method 'Open' of object 'Presentations' failed."

edit2: I think I identified the problem: Another user had the file open, but when I manually opened it he must have had it closed. Now I wonder how to avoid this issue because I don't the macro to fail, much less so with some cryptic error message. I would be happy with read-only, but apparently it doesn't give me that option. Do I have to open every file read-only by default to not run into this issue again?
I've been working on some code and all of a sudden, a very basic line gets me an error message: "Run time error -2147467529 (80004005): Method 'Open' of object 'Presentations' failed. I recreated the problem in this piece of code:
Dim PowerPointApp As PowerPoint.Application
Dim myPresentation As PowerPoint.Presentation
Sub MReport()
Dim DestinationTemplate As String, DestinationAmp As String
Dim PPAmp As PowerPoint.Presentation
Dim AmpName As String, PathAmp As String
DestinationTemplate = "G:\MReport\MReportTemplate.pptm"
PathAmp = "G:\MReport\Amp\MReportAmp\"
AmpName = Dir(PathAmp & "Amp*long*.*")
DestinationAmp = PathAmp & AmpName
Debug.Print DestinationAmp
Set PowerPointApp = New PowerPoint.Application
Set myPresentation = PowerPointApp.Presentations.Open(DestinationTemplate) 'works
Application.DisplayAlerts = False 'doesn't help
Set PPAmp = PowerPointApp.Presentations.Open(DestinationAmp) '<-- error
Application.DisplayAlerts = True
End Sub
The error occurs in the line Set PPAmp = PowerPointApp.Presentations.Open(DestinationAmp). It worked literally dozens of times before. Then I rearranged some code unrelated to this PowerPoint file and shifted it into separate procedures and the error happened. The error now happens in the new, re-arranged file and in the old one, which successfully ran for days.
I tried restarting my computer, MS PowerPoint 16.0 Object Library is also checked. The Debug.Print statement gives me the correct path, I can copy it into the file explorer and the right presentation opens.
The code is written in Excel, but when I copied it into PowerPoint I got the same error. I also tried declaring all the PowerPoint-related variables (PowerPointApp, myPresentation, PPAmp) as Object and then use Set PowerPointApp = CreateObject("PowerPoint.Application") without success.
edit: Typing PowerPointApp.Presentations.Open("Filepath") gives me the same error (I think): "Run time error '-2147467259 (80004005)': Automation error. Unknown error."

Excel still running after close vb.net app

I'm having some problems closing Excel files. I am doing a program that opens some Excel files, uses the information and then close them.
I tried some different codes, but they didn't work because the EXCEL process is still running.
My first code:
Dim aplicacaoexcel As New Excel.Application
Dim livroexcel As Object
Dim folhaexcel As Excel.Worksheet
livroexcel = aplicacaoexcel.Workbooks.Open("C:\Users\LPO1BRG\Desktop\Software Fiabilidade\Tecnicos.xlsx", UpdateLinks:=False, ReadOnly:=False, Password:="qmm7", WriteResPassword:="qmm7")
folhaexcel = livroexcel.sheets("Folha1")
aplicacaoexcel.DisplayAlerts = False
aplicacaoexcel.Visible = False
folhaexcel = Nothing
livroexcel.Close()
livroexcel = Nothing
aplicacaoexcel.Quit()
aplicacaoexcel = Nothing
Then I added this: System.GC.Collect() but it still not closing the Excel process.
Now I am trying this:
Dim process() As Process = system.Diagnostics.Process.GetProcessesByName("EXCEL")
For Each p As Process In process
p.Kill()
Next
Actually, this one is working, but it closes all the Excel files (even those that are not opened by my program).
What can I do to close just the Excel files opened by my program? :)
Releasing the Excel.Application Interop COM object is a little bit trickier than other Office Interop objects, because some objects are created without your knowledge, and they all must be released before the main Application can be actually closed.
These objects include:
The Excel.Application
The Excel.Application.WorkBooks collection
The WorkBooks collection opened WorkBook
The WorkBook Sheets collection
The Sheets collection referenced Worksheet
These objects must all be released in order to terminate the EXCEL process.
A simple solution is to use explicit declarations/assignment for all the COM objects:
Dim ExcelApplication As New Microsoft.Office.Interop.Excel.Application()
Dim ExcelWorkbooks As Workbooks = ExcelApplication.Workbooks
Dim MyWorkbook As Workbook = ExcelWorkbooks.Open("[WorkBookPath]", False)
Dim worksheets As Sheets = MyWorkbook.Worksheets
Dim MyWorksheet As Worksheet = CType(worksheets("Sheet1"), Worksheet)
When you're done, release them all:
Imports System.Runtime.InteropServices
Marshal.ReleaseComObject(MyWorksheet)
Marshal.ReleaseComObject(worksheets)
MyWorkbook.Close(False) '<= False if you don't want to save it!
Marshal.ReleaseComObject(MyWorkbook)
ExcelWorkbooks.Close()
Marshal.ReleaseComObject(ExcelWorkbooks)
ExcelApplication.Quit()
Marshal.FinalReleaseComObject(ExcelApplication)
Marshal.CleanupUnusedObjectsInCurrentContext()
Try something like workbook.Save, workbook.close
I'm a little rusty on my VB and don't have access to Visual Studio right now to test this, but I will try writing the code from memory.
The problem you are running into is that setting an object equal to Nothing still leaves the object allocated in memory and doesn't dispose of the object entirely. Even the Close() and Quit() methods of the object still leave it allocated in memory in case the program needs to access them again later. The Kill() method works because it simply kills the Excel application that is running in memory, which closes any open Excel documents as well as the ones used by COM objects. What you want to do is dispose of the specific COM objects that your application is using.
Try this change in your code though.
Dim aplicacaoexcel As New Excel.Application
Dim livroexcel As Object
Dim folhaexcel As Excel.Worksheet
livroexcel = aplicacaoexcel.Workbooks.Open("C:\Users\LPO1BRG\Desktop\Software Fiabilidade\Tecnicos.xlsx", UpdateLinks:=False, ReadOnly:=False, Password:="qmm7", WriteResPassword:="qmm7")
folhaexcel = livroexcel.sheets("Folha1")
aplicacaoexcel.DisplayAlerts = False
aplicacaoexcel.Visible = False
DisposeComObj(folhaexcel)
DisposeComObj(livroexcel)
DisposeComObj(aplicacaoexcel)
Then add the following to your application as well.
Private Sub DisposeComObj(ByRef Reference As Object)
Try
Do Until _
System.Runtime.InteropServices.Marshal.ReleaseComObject(Reference)<=0
Loop
Catch
Finally
Reference = Nothing
End Try
End Sub
Hopefully my memory is serving me well. I haven't written any code in VB or C# in more than a year and feel very out of practice. I only saw your question because I clicked on the wrong link and remembered how I used to struggle with garbage collection when I started programming.

Empty bmp file when exporting ChartObject from excel sheet in VB.net

A Visual Management Board at my workplace uses an excel spreadsheet, with many sheets in it, to populate a VMB on a TV. These sheets have many charts in them. I don't work a whole lot in VB so please bear with me.
I'm convinced my problem is because the chart the program is trying to access, literally isn't visible in the excel sheet that pops up. I may just not know what I'm talking about but this seems like a terrible way to get and display data. But I'm supposed to fix it. Here's the sheet that pops up on the screen (I've erased some information for privacy reasons):
Here is an example of the bmp being created when it tries to export a chart that is not visible in the excel window:
From my research, I've found many have resolved this issue by Activating the chart object before exporting it. I tried to do that here, but an exception gets thrown. Here's the entire section of code dealing with the charts and exports to make BMPs that are supposed to reside in the Documents folder:
Dim xlApp As Excel.Application
Dim xlWorkBooks As Excel.Workbooks
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheets As Excel.Sheets
Dim xlWorkSheet As Excel.Worksheet
xlApp = New Excel.Application
xlApp.Visible = True
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(ScoreCard)
xlWorkSheets = xlWorkBook.Sheets
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = My.Settings.Org Then
xlWorkSheet.ChartObjects(2).chart.Export(Filename:=path + "\Documents\OnTimeDelivery.bmp", FilterName:="BMP")
picOnTimeDelivery.Image = New System.Drawing.Bitmap(path + "\Documents\OnTimeDelivery.bmp")
xlWorkSheet.ChartObjects(3).chart.Export(Filename:=path + "\Documents\Quality.bmp", FilterName:="BMP")
picQuality.Image = New System.Drawing.Bitmap(path + "\Documents\Quality.bmp")
xlWorkSheet.ChartObjects(1).chart.Export(Filename:=path + "\Documents\NoDemandInventory.bmp", FilterName:="BMP")
picNoDemandInventory.Image = New System.Drawing.Bitmap(path + "\Documents\NoDemandInventory.bmp")
xlWorkSheet.ChartObjects(7).chart.Export(Filename:=path + "\Documents\ExcessInventory.bmp", FilterName:="BMP")
picExcessInventory.Image = New System.Drawing.Bitmap(path + "\Documents\ExcessInventory.bmp")
xlWorkSheet.ChartObjects(4).chart.Export(Filename:=path + "\Documents\Freight.bmp", FilterName:="BMP")
picFreight.Image = New System.Drawing.Bitmap(path + "\Documents\Freight.bmp")
xlWorkSheet.ChartObjects(5).chart.Export(Filename:=path + "\Documents\ShortagesByStart.bmp", FilterName:="BMP")
picShortagesByStart.Image = New System.Drawing.Bitmap(path + "\Documents\ShortagesByStart.bmp")
xlWorkSheet.ChartObjects(6).chart.Export(Filename:=path + "\Documents\ShortagesRootCause.bmp", FilterName:="BMP")
picShortagesRootCause.Image = New System.Drawing.Bitmap(path + "\Documents\ShortagesRootCause.bmp")
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
Next
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
'Close connection to excel sheet
MyConnection.Close()
The program crashes, throwing an Invalid Parameter exception when trying to set
picFreight.Image = New System.Drawing.Bitmap(path + "\Documents\Freight.bmp")
because the Freight.bmp in my documents folder is a 0kb file. If I change what image it's loading next (comment that line out and let it try to load ShortagesByStart.bmp) it crashes for the same reason. All of the charts past this point have one thing in common, they aren't visible on screen. Still this seems like a stupid reason to me; surely something like that wouldn't cause an issue!
First I tried to Activate the xlWorkSheet
xlWorkSheet.Activate()
but this changed nothing.
So I tried to activate the individual ChartObjects by adding
xlWorkSheet.ChartObjects(2).chart.Activate()
xlWorkSheet.ChartObjects(3).chart.Activate()
xlWorkSheet.ChartObjects(1).chart.Activate()
xlWorkSheet.ChartObjects(7).chart.Activate()
xlWorkSheet.ChartObjects(4).chart.Activate()
before the export statements. This actually threw an exception:
So, at this point I'm stuck. How can I activate the chart objects in the worksheet properly? Perhaps there's another problem that's causing this.
So the solution was to update Microsoft Office on whichever PC we wanted to run the VMB from. Corporate creates this Excel spreadsheet with the data on it that this program was trying to display. Eventually, whoever creates this excel sheet got a newer version of Excel, which creates an .xlxs file.
I honestly don't know why the spreadsheet successfully opened in ReadOnly mode, but I suppose there wasn't full support there for Office 2007 and 2010. After upgrading the copy of office on the PC the program created all of the bmps. Weird and I'm sorry if this isn't much of an answer for others but this resolved my issue!

Error when importing an Excel worksheet into Access table

I am getting error Run-time error 3125 'Import$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long when I am attempting to import an Excel file to an Access Table. I only receive this error when other Excel files are open otherwise the Excel file is loaded to the table as expected. Here is some of the code I am working with:
Dim f As FileDialog, str As String
Set f = Application.FileDialog(msoFileDialogFilePicker)
f.Show
On Error GoTo Err1
str = f.SelectedItems(1)
Dim xl As Excel.Application
Set xl = New Excel.Application
xl.Visible = True
Dim xlWB As Excel.Workbook
Set xlWB = xl.Workbooks.Open(str)
'manipulate Excel file
'load spreadsheet
On Error GoTo Err2
DoCmd.TransferSpreadsheet acImport, 8, "JobCode", str, True, "Import!"
I originally thought and tried to change the filename, but was unsuccessful. It seems like the code is opening a new version of the import Excel file as Read-Only which might be confusing the Access database on which worksheet to import. But I am not sure why it's doing this and also why it only does this when another Excel file is open. Is this the problem? Does anyone know how to fix this?
Thank you!

Resources