Use VBA to open a "read-only recommended" Word document and modify it

If I have designated a Word document as "read-only recommended", users have the option of opening it without the "read-only" protection.

Can VBA have the same privilege? I need to change some "read-only recommended" documents and would prefer not to have to do it all by hand.

It is not an important problem, but it comes up so frequently I would like to automate my changes.

With much appreciation,

    --j.r.a.
JohnRobinAllenRetired professor of FrenchAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris BottomleySoftware Quality Lead EngineerCommented:
Hello JohnRobinAllen,

Do you mean:
application.documents.open filename:="myfilespec.doc", readonly:=false

Regards,

chris_bottomley
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
How I wish life were that simple. When I run that command on my computer with a "read-only recommended" document , the code stops and I get a message that says:
     Run-time error '5346':
     Word cannot change the function of the specified key.

Would you or anyone else want to suggest some other method of overcoming the problem?
              j.r.a.
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
Apologies for the error in my last post. My run-time error 5346 was caused by bad code in an AutoOpen function.

Unfortunately, the problem of "read-only" still exists. I can open the document with the code Chris suggested, but after changing it, I cannot save it. VBA balks with the error message
    Run-time error '5155'
    This file is read-only.
(and then it gives the location of the file it cannot save).

If the problem cannot be solved, can I at least find out whether a file I want to open is "read-only recommended"? I hope that will not be the only "solution."

         john robin
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

dotofficeCommented:
Dim d As Document
Set d = Documents.Open("c:\test.docx")
if d.ReadOnlyRecommended then
  'do something here
else
  'or something else here
end if
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
Although I have not tested it yet, that code should solve the problem of detecting whether a file I have opened is read-only recommended.

I would still like to wait a bit and see if anyone else can solve the main problem: how can I use VBA to change a file that was saved as read-only recommended.

Thanks to dotoffice for this help toward the goal.

      j.r.a.
0
Chris BottomleySoftware Quality Lead EngineerCommented:
Try the following which basically saves the document as a temp document and then saveas to overtype the existing document

Chris
Sub Macro1()
Dim doc As Document
Dim wasRO As Boolean
Dim fs As String

    fs = "C:\Documents and Settings\cbottom1\Desktop\ro.doc"
    Set doc = Documents.Open(FileName:=fs, ReadOnly:=False)
    wasRO = doc.ReadOnlyRecommended
    Selection.EndKey Unit:=wdStory
    Selection.TypeText "newline, at " & Now & vbCrLf
    If wasRO Then
        doc.SaveAs Environ("temp") & "\deleteme.doc"
        doc.SaveAs fs
    Else
        doc.Save
    End If
    
    doc.Close

End Sub

Open in new window

0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
Chris, you are a genius. I have used that technique in other situations but never thought of applying it to this problem. You have used dotoffice's and your method to produce an elegant solution. Let me test it out, and then get back to you. In a few hours, I hope, my problem will be solved and I will be eternally grateful.
       j.r.
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
Unfortunately the code still balks at line 13 of the 26609586 message above: doc.SaveAs fs

     It gives the same error message:
  Run-time error '5155'
  This file is read-only.
  (and then it gives the location of the file it cannot save).
 
I may have a way to get around that and, if successful, I will post it here. I am going to select the whole doc, copy the selection, open a brand new document, past the old document info in it, kill the original document, and save the new document under the same name with a "read-only recommended" argument.

The above seems clumsy but it might work.


        j.r.a.
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
The suggestion I made to copy the document into a new document, kill the old document, and save the new document under the old name does not work. Even though the new document is not "read-only recommended" and even though the old document that was such no longer exists, we cannot save the new document under the old, deleted name. A message still appears to say that the file (that no longer exists) is read-only.

I also tried saving the current doc under a new name, "Delete me", and with read-only recommended set to False. I can then change the file and save it under any other name with no problem, but if I use the name of the old, deleted file, it fails. The result is the same. Even though I killed the old file, the computer remembers the name as a "read-only" document and refuses to let me save the document under that name. Any other name is fine, but not that name.

Perhaps the problem has no solution. I am increasing the point value to 500 but I am not optimistic that a solution exists.

          j.r.

0
Chris BottomleySoftware Quality Lead EngineerCommented:
I have just repeated the exercise and it definitely works fine for me.

It therefore begs the question are you referring to the Woerd feature in re recommended read only or a filing system read only document.

If the former then the above code works fine and if the latter then it is a different solution you require.

Chris
0
Chris BottomleySoftware Quality Lead EngineerCommented:
I have modified the sub to accomodate both readonlyrecommended and DOS read only attributes.  See if it helps.

Chris
Sub Macro1()
Dim doc As Document
Dim wasRORecommended As Boolean
Dim wasRO As Boolean
Dim fs As String
Dim fso As Object
Dim fil As Object
Const ReadOnly = 1

    fs = "C:\Documents and Settings\cbottom1\Desktop\dosro.doc"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fil = fso.GetFile(fs)

    wasRO = False
    If fil.Attributes And ReadOnly Then
        fil.Attributes = fil.Attributes Xor ReadOnly
        wasRO = True
    End If

    Set doc = Documents.Open(FileName:=fs, ReadOnly:=False)
    wasRORecommended = doc.ReadOnlyRecommended
    Selection.EndKey Unit:=wdStory
    Selection.TypeText "newline, at " & Now & vbCrLf
    If wasRORecommended Then
        doc.SaveAs Environ("temp") & "\deleteme.doc"
        doc.SaveAs fs
    Else
        doc.Save
    End If
    If wasRO Then
        fil.Attributes = fil.Attributes Xor ReadOnly
    End If
    
    'doc.Close

End Sub

Open in new window

0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
Unfortunately it still bombs out. Image 1 shows where it bombs. Image 2 shows the bomb message.

I will try to massage the code a bit and see if I can get it to work.

       j.r.
Image-1-2-22-2010-11-00-53-AM.jpg
Image-2-2-22-2010-11-01-34-AM.jpg
0
Chris BottomleySoftware Quality Lead EngineerCommented:
I cannot understand! ... what version of windows and word are you using?

Chris
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
I am using Windows XP and Word 2007. I think the problem is more basic than that. As far as I can see, these three lines are to open a document:

    fs = "C:\Documents and Settings\cbottom1\Desktop\dosro.doc"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fil = fso.GetFile(fs)

If so, then on my machine they open no document. Of course I revise fs so that it points to a valid Word 2003 file that has been saved as "read-only recommended." In about twenty minutes I can walk through the steps and describe what is happening.
        j.r.
0
Chris BottomleySoftware Quality Lead EngineerCommented:
Ah

Bear in mind I was running a test at the time and dosr is simply my test file.  Replace that constant with a reference to your file path i.e.

fs = "C:\Documents and Settings\cbottom1\Desktop\dosro.doc"
to
fs = "C:\path1\path2\pathn\myfilename.doc"

Chris
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
I understand that DosR is a test file, and I have revised the code to point to a valid ROR file with a *.doc extension so that Word 2003 can open it.

Nothing I can do changes the problem. I have GoToMyPC and can therefore invite you to go on my computer and test it for yourself, as long as you have a high-speed internet connection. If you would be willing to do that, would you please send me your email and, preferably a phone by which I can phone you. My address is allen@cc.umanitoba.ca. I am tied up for the next forty minutes, but then I am free and will phone you to check that you are free too. If you can solve the problem , I would like to put the solution on these pages. It is now 1:35 p.m. in Pacific Mountain Time (i.e., Denver or Calgary time). I should be back around 2:15 until 4:30 p.m. here. (Calgary, Canada).

         j.r.a.
0
Chris BottomleySoftware Quality Lead EngineerCommented:
No can do sorry, i'll be off bye byes any time now!

Chris
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
Tomorrow, Tuesday, I am busy until ca. 1:00 p.m. Calgary time which is equivalent to 8:00 p.m. in Britain. If that is too late, perhaps we can do something on Wednesday.  
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
I guess there is little hope of finding a solution. I will try some other steps or figure out a work-around, but I am somewhat surprised that Mr Botomley's solution will not work on my machine.
     If I cannot solve the problem myself, I will post a comment with his code and my "read-only recommended" document and see whether he can make it work on his machine.
      j.r.
0
Chris BottomleySoftware Quality Lead EngineerCommented:
J.R.

Where do we stand on this Q.  for example and simply out of interest have you trid it on a different machine?

Chris
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
I do not have a different machine on which to try it. Let me post tomorrow the files in question and the code that does not do the job.
  j.r.
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
I am having trouble making a sample file and modified code to open that file to post here to show how the code does not work.

My problem is that sometimes the code works as specified, and sometimes not. At first I thought it works only if the code modifies the file in some manner, but then again sometimes that is not necessary.

The cases where the code does not work are not in sample files I can post here, files that work with directories that are not on other user's drives.

A little more work should either show me how the code works or will let me post an example of how it does not work.

Back here again soon!
     j.r.a.
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
I finally have a sample that does not work with that code. Perhaps the problem lies in the file I am trying to manipulate.

I have attached a sample file that should be saved (temporarily) to a desktop. I realize that there should be an accent in the name of the file, but EE does not let me keep that accent when I upload the file, so I removed the accent and revised the code to work with the revised name.

The sample code is a modified version of Chris's code to look for the problem file on the desktop.

The code bombs for me, even with an unaccented name.
      j.r.a.
301-Essay-2-Emmanuelle-Beart.doc
0
JohnRobinAllenRetired professor of FrenchAuthor Commented:
My last message got sent before I had added the code.  This is the same message, but (I hope) with both the file and the code.

I finally have a sample that does not work with that code. Perhaps the problem lies in the file I am trying to manipulate.

I have attached a sample file that should be saved (temporarily) to a desktop. I realize that there should be an accent in the name of the file, but EE does not let me keep that accent when I upload the file, so I removed the accent and revised the code to work with the revised name.

The sample code is a modified version of Chris's code to look for the problem file on the desktop.

The code bombs for me, even with an unaccented name.
      j.r.a.
Sub EEMacro1()
Dim Doc As Document
Dim wasRORecommended As Boolean
Dim wasRO As Boolean
Dim fs As String
Dim fso As Object
Dim fil As Object
Dim strDocLoc As String

      Const ReadOnly = 1
      strDocLoc = "C:\Documents and Settings\" & Environ("USERNAME") & "\Desktop\301 Essay 2 Emmanuelle Beart.doc"
      fs = strDocLoc '& fs
      Set fso = CreateObject("Scripting.FileSystemObject")
      Set fil = fso.GetFile(fs)
      wasRO = False
      If fil.Attributes And ReadOnly Then
            fil.Attributes = fil.Attributes Xor ReadOnly
            wasRO = True
      End If
      
      Set Doc = Documents.Open(FileName:=fs, ReadOnly:=False)
      wasRORecommended = Doc.ReadOnlyRecommended
      '     Selection.EndKey Unit:=wdStory
      '     Selection.TypeText "newline, at " & Now & vbCrLf
      If wasRORecommended Then
            Doc.SaveAs Environ("temp") & "\deleteme.doc"
            Doc.SaveAs fs
      Else
            Doc.Save
      End If
      If wasRO Then
            fil.Attributes = fil.Attributes Xor ReadOnly
      End If
      Doc.Close
End Sub

Open in new window

301-Essay-2-Emmanuelle-Beart.doc
0
Chris BottomleySoftware Quality Lead EngineerCommented:
I have no idea why it should work in my tests but not for you BUT thank you for the file I have reproduced the issue using the supplied data.  I dad have an issue with the file name but I think that was a duff character code in the string so be warned just in case.

The attached code takes longer as it creates a new instance of word with which to saveas, but seems to work.

Let me know how it looks.

Chris
Sub EEMacro2()
Dim Doc As Document
Dim wasRORecommended As Boolean
Dim wasRO As Boolean
Dim fs As String
Dim fso As Object
Dim fil As Object
Dim strDocLoc As String
Dim wasApp As Object
Dim newApp As Object
 
      Const ReadOnly = 1
      Set wasApp = Application
      strDocLoc = CStr("C:\Documents and Settings\" & Environ("USERNAME") & "\Desktop\301 Essay 2 Emmanuelle Beart.doc")
      strDocLoc = CStr(Environ("userprofile") & "\Desktop\301 Essay 2 Emmanuelle Beart.doc")
      fs = strDocLoc '& fs
      Set fso = CreateObject("Scripting.FileSystemObject")
      Set fil = fso.GetFile(fs)
      wasRO = False
      If fil.Attributes And ReadOnly Then
            fil.Attributes = fil.Attributes Xor ReadOnly
            wasRO = True
      End If
       
      Set Doc = Documents.Open(FileName:=fs, ReadOnly:=False)
      wasRORecommended = Doc.ReadOnlyRecommended
      '     Selection.EndKey Unit:=wdStory
      '     Selection.TypeText "newline, at " & Now & vbCrLf
      If wasRORecommended Then
            Doc.ReadOnlyRecommended = False
            Doc.SaveAs Environ("temp") & "\deleteme.doc"
            Set newApp = CreateObject("word.application")
            Doc.Close
            Set Doc = newApp.Documents.Open(FileName:=Environ("temp") & "\deleteme.doc")
            Doc.SaveAs fs
      Else
            Doc.Save
      End If
      If wasRO Then
            fil.Attributes = fil.Attributes Xor ReadOnly
      End If
      Doc.Close
      If Not newApp Is Nothing Then newApp.Quit

End Sub

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JohnRobinAllenRetired professor of FrenchAuthor Commented:
The new code works beautifully, at least once, and that is enough to award full points. There is absolutely no reason to think it will not work always.

I apologize for the delay in checking out the code.

My gratitude. I hope the code will be of use to others too.
       j.r.a.
0
Chris BottomleySoftware Quality Lead EngineerCommented:
Note if this is to be done on multiple documents at run time it should be posssible to speed up the repeats if the collection of documents to work on can be evaluated.

Chris
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Office

From novice to tech pro — start learning today.