Excel VBA Workbook.ChangeFileAccess

风格不统一 提交于 2019-12-22 12:48:11

问题


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 access 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.aspx

Is it possible to change between file access modes as I am trying to do?


回答1:


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



来源:https://stackoverflow.com/questions/5030336/excel-vba-workbook-changefileaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!