Excel VBA Workbook.ChangeFileAccess
I'm having trouble with changing the file access mode on Excel workbooks using VBA. I am using Office 2010.
I want to be able to alternate between read only and read write mode as appropriate. However it seems changing a workbook from read/write to read only and then back again as in the code below causes an automation error when trying to access any member of the workbook object.
Public Sub example()
Dim w As Workbook
'open workbook with write access
Set w = Workbooks.Open("example.xlsx", ReadOnly:=False)
Debug.Print w.Name 'sucessfully accesses members of w
'change file access to read only
w.ChangeFileAccess XlFileAccess.xlReadOnly
Debug.Print w.Name 'successfully accesses members of w
'change file access back to read/write
w.ChangeFileAccess XlFileAccess.xlReadWrite
Debug.Print w.Name 'fails to acce开发者_高级运维ss members of w with automation error
End Sub
I don't understand why this is the case. It is obviously perfectly possible to open a workbook as read only, change it to read write and then continue to use the object. Why is this situation different? I can find no mention of this behaviour on MSDN.
http://msdn.microsoft.com/en-us/library/ff193344.aspxIs it possible to change between file access modes as I am trying to do?
I think you've hit an interesting foible with the way that Excel changes the read/write state. In order to switch a workbook from read-only to read/write, Excel closes that workbook and opens it again. During this process, your object reference turns into something strangely broken. If you add the line:
Set w = Workbooks("example.xlsx")
after you ChangeFileAccess to xlReadWrite then it perks up again, but it's not exactly ideal.
Chris
精彩评论