Skip automatically pop up for protected workbooks - vba

I use at the moment the following command to open a set of workbooks one by one:
Workbooks.Open Filename:=fFile, Password:="", UpdateLinks:=xlUpdateLinksNever, ReadOnly:=False
Normally the files are open in write-enabled mode, which is what I want. But for some files, the previous line pops up the following window:
In this case, I need to press Read Only to open it. Even though it is read-only, it is still good to be able to open it.
So to conclude, I try to open files in write-enabled mode, if it is not possible for some files, opening them in read-only is still fine. But as the number of the files is huge, I really want to automatize it, and avoid this pop-up. Could anyone tell me how to do it?
One possible turnaround is to first opening all the files in read-only mode, then convert them to write-enabled mode if possible. Do you think that is doable?

This is possible workaround for you. The idea is to pass any incorrect password to WriteResPassword argument. If file is protected the error will be thrown. If so you will be able to identify that file and open it in read-only mode. Alternatively, password will be ignored for other files and fill will be open for read-write mode.
Some additional comments within code below.
Sub PossibleWorkaround()
Dim Pass As String
'any password
Pass = "blahblah"
'file which is write-protected will throw error during opening it _
with incorrect password
On Error Resume Next
Workbooks.Open "c:\users\alpha\desktop\filename.xlsx", , , , , Pass
If Err.Number = 1004 Then
'if so, try to open it in read-only mode
Workbooks.Open "c:\users\alpha\desktop\filename.xlsx", , True
End If
'return to standard error handling or set as expected
On Error GoTo 0
'the same for file which is not write-protected
'incorrect password will be ignored
On Error Resume Next
Workbooks.Open "c:\users\alpha\desktop\filename A.xlsx", , , , , Pass
If Err.Number = 1004 Then
'therefore this if statement will not be called
Workbooks.Open "c:\users\alpha\desktop\filename.xlsx", , True
End If
On Error GoTo 0
End Sub

I had the same problem. I tired to find the answer on many formums and nothing. Finally I added WriteResPassword:="password here" in the end of the Worksbooks.Open statement and it did not prompt for a password anymore
Workbooks.Open Filename:="\path to the file\File_name.xlsm", Password:="password here", WriteResPassword:="password here"

Related

Deleting a file immediately after closing it - 'Permission Denied' error

I want to save an email as a Word file through a macro, and then replace this with a converted PDF file via Word. The conversion part is working fine - the issue is when I try to delete the original .doc file.
Dim objWrd As Object
Dim objWrdDoc As Object
Dim wrdCurrentPrinter As String
Set objWrd = CreateObject("Word.Application")
Set objWrdDoc = objWrd.Documents.Open(filePath & fileName)
''Print' file as PDF - current printer is stored so it can be reverted back afterwards
wrdCurrentPrinter = objWrd.ActivePrinter
objWrd.ActivePrinter = "Microsoft Print To PDF"
'File name is specified here to avoid Save As prompt. PrintToFile property is 'True'
objWrd.PrintOut , , , filePath & Replace(fileName, ".doc", ".pdf"), , , , , , , True
objWrd.ActivePrinter = wrdCurrentPrinter
objWrd.Quit
Set objWrd = Nothing
Kill filePath & fileName
At Kill filePath & fileName I get error 70 - Permission denied.
I am able to delete the file manually without any problems, and if I add a breakpoint and step through the 'Kill' line, it works when there is even a slight delay between Word closing and the Kill command. Therefore I suspect that the code is being processed so quickly so that the file is still open at the time of running the command.
I have a feeling I may need to go down the route of creating a delay, which I have been having trouble with in Outlook. Is this the likely solution or is there something else that I have missed?
I have been able to get this to work consistently by simply closing the Word document before quitting Word altogether:
objWrdDoc.Close
objWrd.Quit
Set objWrd = Nothing
The error has not appeared since adding this line and testing with various emails.

vba Excel - How to Check if a SharePoint Website File is Open

I've searched the internet for the answer to this and keep running into issues getting it to work.
I need to check if a file at the below location is open/locked, and then have the code wait 15 seconds and then try again. Right now if someone else has the file open a dialog box opens asking if I want to open read only, which I don't want. I tried using Application.DisplayAlerts = False to get the message not to appear but that didn't seem to work. So I have two main issues:
Checking if the file is open and waiting to try again.
Stop the dialog box from opening asking to open as read only.
Workbooks.Open filename:= _
"https://somecorporatewebsite/sites/TNKYWest/Engr/ASE%20Updates/Shared%20Documents/ASENW Updater.xlsx"
Try something like this:
From MSDN site:
https://msdn.microsoft.com/en-us/library/office/ff193284.aspx
Sub UseCanCheckOut(docCheckOut As String)
Dim docCheckout
set docCheckout="File name to open"
' Determine if workbook can be checked out.
If Workbooks.CanCheckOut(Filename:=docCheckOut) = True Then
Workbooks.CheckOut (Filename:=docCheckOut)
Else
Found at the MSDN Website:
https://msdn.microsoft.com/en-us/library/office/ff822851.aspx
Application.Wait(Now + TimeValue("0:00:10"))
Workbooks.CheckOut (Filename:=docCheckOut) 'Try to check the file out again.
End If
End Sub
This part is covered in the
IF workbooks.cancheckout(filename:=docCheckout)=true then workbooks.checkout ' method in part 1.

Use VBA to retrieve and call VBA code from a text file

I am working on a project to process some incoming Outlook messages using rule-triggered VBA code.
However, I don't want to have to manually update the code for each user's inbox any time the code needs to change. So my idea is to put a text file on a shared drive and have the VBA pull that text file down and treat it like code. Essentially, I want to use that text file like a little code library.
I was able to find this link that has gotten me very close to my goal. However, I'm having a few issues with it.
Here is the code I put together. It is attached to the click event of a Rectangle shape I inserted into an Excel file. Eventually, I'll move this over to Outlook, but I'm just doing a basic test with Excel VBA first.
Sub Rectangle1_Click()
On Error GoTo Err_Handler
Dim enviro As String
Dim myFile As String
'Pull code "library" from text file on user's desktop
'This will eventually be changed to reside on a shared drive
enviro = CStr(Environ("USERPROFILE"))
myFile = enviro & "\Desktop\hello_vba.txt"
'If the "Library" module already exists, delete it
For Each a In Modules
If a.Name = "Library" Then
a.Delete
Exit For
End If
Next
'Add a new module
Set m = Application.Modules.Add
'Rename it to "Library"
m.Name = "Library"
'Insert the text from the other file to this new module
m.InsertFile myFile
'Call the hello() subroutine from the retrieved text file
Library.Hello
Exit_Here:
'Cleanup code goes here
Exit Sub
Err_Handler:
MsgBox Err.Description
Resume Exit_Here
Exit Sub
And here is the content of the external text file named "hello_vba.txt":
Sub Hello()
MsgBox "Hello"
End Sub
The first time I run this, using the debugger I can see that it creates the new module and then gets to the line that says:
m.Name = "Library"
And then a window pops up in the debugger that says:
Can't enter break mode at this time
When I click continue on that message, I get an
Object Required
error message. If it run it again, then I get some more error messages but I do eventually get a successful "Hello" message box pop up.
I'm wondering if I may not have "Dim"ed the "a" or "m" variables properly or if there is a problem trying to pull in a text file and immediately treat it like code?
Any ideas?
To run your new code, try using Application.Run instead of Library.Hello
It would be written:
Application.Run("Hello")
Does that work?

Publish an excel worksheet as an HTML file using a command button

So I have tons of data in my workbook that I need to pass on to my users in a way that allows them to interact with the workbook..., but also limits what they can actually do. So I have made it so they can access certain pages to Add needed data, then I've given access to a menu page so they can run a report.
This report I have found is best if it's an html page.
To that end, I have tried several different ways, save as...and publish. I like the publish version, but I can not for the life of me get this working. All the samples I see, appear to be the same. Here is the line of code in question:
ActiveWorkbook.PublishObjects.Add(xlSourceSheet, ActiveWorkbook.Path & ".htm, "Sheet1", "", xlHtmlStatic, "", "Report Title").Publish True
Every time I get a run time error '1004':
Method 'Publish' of object 'PublishObject' failed
I have the above line of code in a sub, am I missing something? Do I need to set up the publish differently? Thanks for any ideas.
I have had a similar mysterious problem that sometimes it (.Publish) works and sometimes it doesn't, when I try publish.
However, I think the problem might be, in cases when it doesn't work right off the bat, to first save the relevant region as a webpage so that it exists already on the server. After that region has been saved at least once (manually or else maybe with .SaveAs .. see below), then the publish might work.
Here is an example of how I get this to work more consistently, something to convey the structure that works for me:
wkb=ActiveWorkbook.Name 'save wb for later access
url="http://a.com/b.htm" 'save to Internet
sheetname="c"
Sheets(sheetname).Range("d1:e2").Select 'activating sheet may be necessary
On Error Resume Next 'anticipate error to handle it
'Now comes the publish line the first time... which may work.. or not
ActiveWorkbook.PublishObjects.Add(xlSourceRange,url,sheetname,"d1:e2",xlHtmlStatic,"blah","moreblah").Publish (True) 'may fail to create page on website if page didn't already exist
theerr=Err.Number
On Error GoTo 0 'back to default error handling (none)
If theerr <> 0 Then 'if here perhaps because page nonexistent
'msgbox "maybe add warning here [FYI]"
Sheets("dummysheetwithlittleornodata").Copy 'will create workbook
On Error Resume Next
ActiveWorkbook.SaveAs url 'may fail to create webpage first time
ActiveWorkbook.saveAs url 'twice needed for some reason sometimes. [works for me]
On Error GoTo 0
'with fresh dummy html page created, now publish should hopefully work.. let's try again
ActiveWorkbook.Close savechanges:=False 'clean up and avoid popup
Workbooks(wkb).Activate 'get back to correct wkb
Sheets(sheetname).Range("d1:e2").Select
ActiveWorkbook.PublishObjects.Add(xlSourceRange,url,sheetname,"d1:e2",xlHtmlStatic,"blah","moreblah").Publish (True) 'hopefully if failed first time, now it succeeded ! good luck.
End If
The above code structure has allowed me to solve several publish problems I was having. All the techniques together have been enough so far to allow me to save a range from a sheet as a webpage (to server I have write access to) without having to do anything manually (like a manual save or even click on popup). Good Luck.
[The different non-obvious techniques include activating a range before trying a range publish, using the error handling approach and anticipating failure at certain points, the 2x saveas to compensate for mysterious inconsistent failures when using one saveas only, closing and getting back to original workbook cleanly, and using saveas to "guarantee" page exists in form that will make publish to succeed more consistently.]

vba Dir(sharePointPath) return empty after saveAs unless manually refresh the folder

I'm saving a excel file one share Point into text file. after the saving, I wanna check Dir(sharePointPath).
It will always return "" unless I manually refresh the corresponding folder.
the code would be like the following:
ActiveWorkbook.SaveAs sharePointPath, xlTextWindows
ActiveWorkbook.Close
While Dir(sharePointPath) = ""
MsgBox "not exist"
Wend
The reason I wanna check Dir(sharePointPath) is that I wanna open that file later
open sharePointPath for binary access read as
which always override the text file because open can't find the file.
what should I do to fix this problem?
EDIT:
sharePointPath = {server}\rule_books\Shared Documents\Rule books\NAME - Demo and Testing Client\Text Files\test.txt before saveAS and after close.
dir(sharePointPath) = "" before and after. occasionally dir(sharePointPath) = test.txt.
but if I wait for a while after close to excute dir(sharePointPath), it will return test.txt more often. i guess vba take some time to write and show the new file.
I gave up, and create a local tmp file on user's end machine for work around