Excel Object SaveAs, error happens when Existing File is Open - excel

Excel_Obj = CREATE OleObject
Excel_Obj.ConnectToNewObject( 'excel.application' )
Excel_Obj.Workbooks.Add
Excel_Obj.Application.ActiveWorkbook.WorkSheets.Add
Excel_Sheet = Excel_Obj.Application.ActiveWorkbook.WorkSheets[1]
//EXAMPLE
Excel_Sheet.Cells[1,1] = 45
Excel_Obj.Application.ActiveWorkbook.SaveAs(ls_file,56) //csv
//where ls_file = the Opened File
error happened after / during saveas.
try catch throw "error calling external object..in click..line.. saveas.."
--
i want to state to the user that the excel file is open therefore cannot be overwritten properly. I used a try catch and throwed a proper message but before the messagebox for the catch event happens, the PB execution error R0035 happens. any solutions or proper way to know if the excel file is open.

You might be able to check if the file is open first, have a look at this answer:
how to check if file is opened in excel using OLE (leaves excel process open)

I'd try a PowerScript FileOpen () call with a LockReadWrite! parameter to see if it can be opened, followed immediately by a FileClose () if it was successful. (I think this is a PowerScript-specific variation on the DXL solution Colin linked to.)
Good luck,
Terry

Have you tried approaches similar to these?
Using Win32 API:
http://www.rgagnon.com/pbdetails/pb-0030.html
Using PB function fileopen()with the (default) exclusive rights set:
http://www.tek-tips.com/viewthread.cfm?qid=1610670
In other words, see if the file can be opened exclusively before connecting to Excel or making the CSV?

You will have to turn off the option to break into the debugger for that exception to see the exception handling work in the IDE. Look for the Help topic "Exception Settings dialog box" for details. Once you see it's working I recommend you set it back to break into the debugger, since you'd normally want to see what threw the error.

You cannot use ole when document is open( even you set lock write) by the user and not by apllication.
my approach, I have been using many times till now:
Check excel is open or not, use use can use api or wsh script in the internet to check app opened. If opened do not run save as and tell user to close excel and not run it for while for while.
if you user run excel and your program still running active workbook and worksheet application will be switch to excel that opened by user ( imagine it wrong written data).
Change your code as below
if Excel_Obj.ConnectToNewObject( 'excel.application' ) <> 0 then
messagebox("warning", "could connect to excel", stopsign!)
RETURN
end if
just for knowledge another technique is DDE call, but not common today and most complicated.
Happy coding From pb developer.

Related

How to stop from deleting a file/workbook in MS excel when it is already open?

We have designed Microsoft Addins for MS Excel and Word 2019 written in VB.net.
There we have designed a tab, on clicking this tab, we open a Task Pane.
On loading this task pane, we execute a code to launch another Excel File/Word file.
So when I delete a file in MS Word that is already open it shows an exception The file 'Filename' already exists.
Given below is the code snippet I am using to delete an already existing open file named processFile
My.Computer.FileSystem.DeleteFile(processFile)
Now when I run the same code snippet in MS Excel it does not show this exception and deletes the file.
I am not able to understand this behavior.
Kindly suggest if anyone has understanding on it
Here is some more information about which environment I'm working in:
Operating System : Microsoft Windows 10 Pro
Code Editor : Visual Studio 2019
Technology : Vb.net(.Net Framework 4.8)
MS Office Version : 2019(32 bit) : Microsoft Windows 10 Pro
The IOException should be thrown if the file is in use. You need to close any editors first and then delete files.
Check if the file is open. I have a code below that may help.
As import sfile use the fullpath with filename. (eg. "C:\Windows\test.txt")
returns True when file it's open and false when it isn't.
Yu will need "Imports System.IO"
Public Function IsFileInUse(sFile As String) As Boolean
Try
If File.Exists(sFile) Then
Using f As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
End Using
End If
Catch Ex As Exception
Return True
End Try
Return False
End Function
As per the information in the comment section, the file is opened in "protected mode" and you are saying that it is deleting while it is still open to the user.
So yes, if the file is engaged and deleted by some program, it should throw an exception and not delete. But if no exception is coming, i.e. some specific handling has been done by Windows/MS Excel so that file has been deleted while it is still kept on buffer and open. Its answer can be given by Microsoft only.
One solution, I can suggest is to close the "protected object" and then delete the file so that no file will be opened to the user and it will be safely deleted.
Snippet to open the file for Add-ins(VSTO):
Dim objProtectedMode As String objProtectedMode = Globals.Connect.Application.ProtectedViewWindows.Open(fileLocation, , False, False)
Snippet to delete the file safely:
If Not (objProtectedMode Is Nothing) Then
objProtectedMode.Close()
End If
My.Computer.FileSystem.DeleteFile(objProtectedMode)
Note: - Solution may vary for other add-ins. Code snippet provided for VSTO Add-ins.

Excel file remaining locked for editing after use

I have a Windows Forms application with an OpenFileDialog. The user clicks a "Process" button and the application goes through the file - an Excel spreadsheet - and processes the data in it. All of this works as expected with one caveat.
After the application is done processing, the file remains locked for editing so when I open the file to make changes, I get this message:
If I close the application completely, the file is unlocked so I'm assuming the application is just holding onto the file for longer than it should. I'm guessing there should be some sort of Close() method or something that will release the resources but I can't figure out exactly what I need. I tried using Dispose() and wrapping my code in a Using block which I thought destroyed everything automatically but no luck.
Here's my code:
Using excel = New ExcelPackage(OpenFileDialog1.OpenFile)
Dim ws = excel.Workbook.Worksheets.First()
'Process data in ws...
OpenFileDialog1.Dispose() 'Doesn't seem to release the file
excel.Dispose() 'Doesn't seem to release the file
End Using
The OpenFileDialog.OpenFile Method returns a Stream object that likely is not being closed by the ExcelPackage.
To ensure that the stream is released, use the following pattern.
Using strm As IO.Stream = OpenFileDialog1.OpenFile
Using excel = New ExcelPackage(strm)
' ...
End Using
End Using

Constantly getting Err 1004 when trying to using Application.AddIns.Add

I'm trying to implement a bootstrap installer for my add-ins workbook, such that I can easily install the add-in for new users and send out updates. It works fine on my machine, but when having others test it, I get a runtime error when I try to call Set AI = Application.AddIns.Add(fileName:=fullPath, copyfile:=True). Specifically, the error is "1004: Unable to get the Add property of the AddIns class". I thought this was because the user needed to have "Trust access to the VBA project object model" enabled, but the error seems to occur even after they've toggled that box.
Other things I've checked:
The fullPath to the add-in is valid and the user can access the directory and the file
The user has the folder located at Application.UserLibraryPath
Any ideas?
Figured it out. It appears that the issue isn't one of permissions, but rather of whether a workbook is already open. Opening any workbook before running the Addins.Add prevented the error from occurring so I've simply added that into the program:
If Application.Workbooks.Count = 0 then Set wb = Application.Workbooks.Add()
Set AI = Application.AddIns.Add(fileName:=fullPath, copyfile:=True)
If not wb is nothing then wb.Close
Duke, perhaps it's the Trust Center settings on the recipients' machines. I have found this and may be helpful.
Best,
Danny
Check out VBA videos on ExcelVBADude on YouTube.

xlsread、xlswrite not work in matlab

matlab (2015b) in my new notebook ThinkPad function xlsread/ xlswrite not work
for every exist excel file, xlsread not load the data
xlswrite also not work in every path
error use xlsread (line251)
catch exception
if isempty(exception.identifier)
exception = MException('MATLAB:xlsreadold:FormatError','%s', exception.message);
end
throw(exception);
the method import data also not work for excel file。
I found this answer in
https://cn.mathworks.com/matlabcentral/answers/282688-why-my-excel-file-can-not-be-read-by-matlab hope it can help you:
Who has problem to read excel file, can follow this order.
1- open the excel> file, >option, >add in, manage then select COM ADD IN, and clear everything (unchecked). everything should be cleared (unchecked).
2- restart the PC, and open the matlab.
3- perform xlsread command.
NOTE: for those people who use foxit pdf reader, it is potential to face this problem, so follow mentioned order.
NOTE: sometimes by using the matlab, configuration of excel is changed in unknown way, therefore there is no way to open the usual excel file in windows by double click.
So, open excel from desktop icon, file> option,> advanced,> general and then make clear (unchecked) "the ignore applications that use dynamic data exchange (DDE)". (same information for NOTE 2: https://support.microsoft.com/en-us/kb/3001579) these are some error for excel worker with matlab and related command.

Error while using actxcontrol in Matlab to clear contents in an open Excel file.

This is my code to clear the excel file I have opened.
% get running excel file
Excel = actxGetRunningServer('Excel.Application');
ExcelFile = Excel.get('Workbooks','usbTC0832.xls');
ExcelSheet = ExcelFile.Sheets.Item('Sheet1');
ExcelFile.Worksheets.Item('Sheet1').Range('A2:C520').ClearContents
% ExcelFile.Save;
Pretty straightforward and it works perfectly in another system. In my new system however it throws up the error
>>Error using COM.Excel_Application/get
>>Invoke Error, Dispatch Exception: Invalid index.
It works fine the first time right after I restart my system. Every instance afterwords it throws up that error. I've tried restarting matlab but it doesn't go away. I seem to need to restart my system. I can't understand what the problem is. Any help would be appreciated.
It may be that the get on Workbooks tries to open the file.
But if it is already open, it will raise an error.
Try to look for it first, with Excel.Workbooks.Item('usbTC0832.xls').
That also could give an error if it is NOT open, you should capture it and if not open, use the get.

Resources