How to open Locked for Editing file as Read Only? - excel

I have a macro that opens multiple files. If it comes to a file "Locked for Editing" it will give me an error saying
FileName is currently in use. Try again later.
How can I make it open said file as read only? I tried:
Workbooks.Open FileName:=Selected_EOS_Report_File, ReadOnly:=True
and
Workbooks.Open FileName:=Selected_EOS_Report_File, ReadOnly:=True, IgnoreReadOnlyRecommended:=True
Update: The first method does work. My code runs on multiple files that pass through the "Selected_EOS_Report_File" variable. At some point a file passed through that was an Excel temp file (begins the filename with "~$"). I created an if/then statement to skip over any such files.

As far as I know, you need Notify:= True
MSDN link
Notify
If the file cannot be opened in read/write mode, this argument is True
to add the file to the file notification list. Microsoft Excel will
open the file as read-only, poll the file notification list, and then
notify the user when the file becomes available. If this argument is
False or omitted, no notification is requested, and any attempts to
open an unavailable file will fail.

The code below worked for a similar Problem I had. This will set the ReadOnly and IgnoreReadOnlyRecommended parameters.
I tested this for Excel 365.
ReadOnly: True to open the workbook in read-only mode.
IgnoreReadOnlyRecommended: True to have Microsoft Excel not display the read-only recommended message (if the workbook was saved with the Read-Only Recommended option).
dim wbReadOnly as Workbook
Set wbReadOnly = Workbooks.Open(strXLSFileName, , True, , , , True)
link to VBA Documentation

Try this?
Dim wb As Workbook
Set wb = GetObject(Selected_EOS_Report_File)
wb.Open 'ReadOnly:=True (removed the readonly part)
Derived from this post: Opening .xlsx with VBA, File in Use error. Read-only not working
edit
A post here indicates a similar issue for older versions, and that if you undate to xlsx then it goes away:
https://social.technet.microsoft.com/Forums/en-US/5c9f7444-a2c7-4598-beca-21a6d5575d94/excel-file-currently-in-use

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.

UserInterfaceOnly = True is discarded when opening a file

I have an Excel+VBA file named "Myfile.xlsm" which needs that UserInterfaceOnly = True property so the VBA code can perform many operations without the user being aware.
I did place the following code to set UserInterfaceOnly = True property in the Workbook_Open event (also tried in the Workbook_Activate event) of "Myfile.xlsm".
Private Sub Workbook_Open()
Dim WSh As Worksheet
For Each WSh In ThisWorkbook.Worksheets
WSh.Protect Password:="myPWD", UserInterfaceOnly:=True
DoEvents
If WSh.ProtectionMode = False Then MsgBox "UIFOnly Init Failed on " & WSh.Name & " !!"
End If
Next WSh
End Sub
In some cases the UserInterfaceOnly is not set as expected and I get the "UIFOnly Init Failed on " message at opening "Myfile.xlsm" and as a consequence many other problems later.
EVEN BETTER: I created a new very simple "UnlockUIFOnly.xlsm" file which has the same code in Private Sub Workbook_Open().
If I open "UnlockUIFOnly.xlsm" first, protection works as expected. If I then open "Myfile.xlsm" (keeping "UnlockUIFOnly.xlsm" open) it works as expected.
If I close both files and open ONLY "Myfile.xlsm" it fails again.
I'm running Office 365 (version 2203 Build 16.0.150028.20512) 32 bits with Windows 10.
FURTHER OBSERVATION #1: I copied this not working "MyFile.xlsm" from its original directory to a new one.
When I opened it from its new directory, I got a banner to enable contents, and I answered yes. Then everything went smooth (No UIFOnly Init Failed on " message, no error 1004 ...). I checked some functionalities, so Excel asked whether I wanted to save changes, answered yes, then later if I wanted that document to be a trusted document, answered Yes as well.
At second open, I did not get any banner to enable contents (normal) but the problems were back.
FURTHER OBSERVATION #2: I again copied this not working "MyFile.xlsm" from its original directory to a new one.
When I opened it from its new directory, I got a banner to enable contents, and I answered yes. Then everything went smooth (No UIFOnly Init Failed on " message, no error 1004 ...). I checked some functionalities, so Excel asked whether I wanted to save changes, answered YES, then later if I wanted that document to be a trusted document, answered no. All further open tentatives asked to enable contents (answer yes) but were smooth.
It looks like declaring a document as trusted bypasses something or changes in which order events are generated, and has a huge impact on my problem

How do I upload a file to OneDrive Business (Sharepoint) with VBA

I'm trying to find a method to upload a file to Onedrive from VBA in Excel.
I've done a lot of searching for acceptable methods, but most methods will not work for my scenario or the proposed solution will give an error.
I can upload files just fine if I'm using UNC paths or OneDrive locations that are synced locally (e.g. "C:\Users(username)\OneDrive\File Share") but I need a method that lets me push(upload) files to a shared URL location (e.g. "https://my.sharepoint.com/:f:/r/personal/(email_address)/Documents/SharedFiles?csf=1&e=6WmUIO"). All the users that will need to use the tool will have access to this shared location in OneDrive.
I tried the normal "SaveAs" method in VBA but that won't work.
Set Excelwb = ThisWorkbook
Excelwb.SaveAs fileName:="https://my.sharepoint.com/:f:/r/personal/(email_address)/Documents/SharedFiles?csf=1&e=6WmUIO" _
, FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=xlLocalSessionChanges
Excelwb.Saved = True
Excelwb.Close SaveChanges:=False
Application.DisplayAlerts = True
I expected this to save the file, but I understand that since I'm saving to a URL and not a local file that another method is probably required, but I can't find one that will work.
The error I'm getting is:
Run-time error '1004'
Method 'SaveAs' of object '_Workbook' failed
I just tried this and it worked fine:
Activeworkbook.SaveAs "https://myComany.sharepoint.com/Departments/dept1/Documents/FGH/Text.xlsx"
To get the required path, browse to the destination in IE, then use Library tab >> Open with Explorer to open the destination in Windows Explorer: you can copy the path from the address bar there.
Maybe this will help someone pulling their hair out. Make sure and spaces in your SharePoint URL are replaced by %20. Example "New Folder" should be "New%20Folder, or remove the space from the folder name.

VBA Error 1004 - ChangeFileAccess Method Failed - File on Sharepoint

I'm fixing some code written by a colleague and I've come across this hurdle where an Excel document is opened from a Sharepoint and the ChangeFileAccess method is run to change it to Read/Write. The method fails with error code 1004. The file opens so everything up to that point is working.
I can't see why it won't work, I'm hoping someone more knowledgeable than I can!
I've removed the file path and document name for the sake of anonymity.
I'm using Office 365, code in question below:
Dim ObjFileA, ObjfileB As File
FilePathA = "filepath" & fileName
Set FSO = CreateObject("Scripting.FileSystemObject")
Set App = CreateObject("Excel.Application")
Set ObjFileA = FSO.GetFile(FilePathA)
Set wbA = Workbooks.Open(ObjFileA, False, False)
wbA.Activate
wbA.ChangeFileAccess (xlReadWrite)
Set wbA = Workbooks(fileName)
Is your file already being opened as Read-Write?
I just encountered a similar problem to what you describe (Err 1004 when changing the access method, though in my case I was attempting to change the access to Read-Only on a file that was already Read-Only.)
After some testing, I get the error every time if I try to invoke wkbk.ChangeFileAccess to "change" the access type to be the same as the current access type.
If you find that the workbook might already be Read-Write, then I suggest a change to :
If wbA.ReadOnly then wbA.ChangeFileAccess (xlReadWrite)

Excel fails to throw errors on Workbooks.Open or Workbook.Save methods on files that are in use

Our code essentially does the following:
1) It creates an Excel.Application object, and invokes .Workbooks.Open to open a file from a network location
2) It makes a minor change to the open Workbook
3) It invokes the .Save() method to save the workbook
This is causing a problem when the file is currently in use because
1) NO error is raised on .Workbooks.Open - The workbook simply gets opened in ReadOnly mode, but no messages or nothin' are shown to the user. So unless the user pays close attention and looks at the Title Bar, he or she will have NO idea that the document has actually been opened in ReadOnly mode
BUT the worst thing is
2) The .Save() method on the WorkBook object raises NO error WHATSOEVER. Instead it just goes ahead and saves the document to the %UserProfile%\Documents folder. Not only does it raise no error that WE can catch in code, it shows no message or warning to the USER either, so they remain blissfully unaware of the fact that they are no longer working on the original document in the Network Location, but on a local copy of same instead.
So the questions are:
1) Can we either force Excel to show a message to the END USER or raise an error on the .Workbooks.Open method so we can handle it in code? At the moment all I can do is check the workbook's .ReadOnly property, but that will give me no clue as to whether the workbook is ACTUALLY Read Only, or whether it was open in Read Only mode because it is in use by another user, let alone tell us in code, or the user through a message box, by WHOM the workbook might be in use.
2) Can we force Excel to raise an error or prompt the user on the workbook's .Save method, rather than simply saving it somewhere local without any indication to anyone!?!?
Sorry if I sound exasperated.... you should have heard the customer....
'Please note that oXApp is a Microsoft.Office.Interop.Excel.Application that has been instantiated correctly.
Dim oWBS As Microsoft.Office.Interop.Excel.Workbooks = Nothing
Dim oWBK As Microsoft.Office.Interop.Excel.Workbook = Nothing
oWBS = oXApp.Workbooks
oWBK = oWBS.Open(sFile) 'No error raised here, nothing. Document is opened in ReadOnly mode. sFile contains a UNC path to a file that is in use by another user.
oWBK.Save() 'Again, no error raised, but while oWBK.FullName points at the UNC path BEFORE the Save, it now refers to a local path in %UserProfile%\Documents

Resources