简体   繁体   中英

Overwrite an excel workbook when it is opened -VBA code

使用VBA代码打开Excel文件时,是否有任何方法可以覆盖它?

I think you can't overwrite a file that is open. This is a windows limitation and as far as I know it is not possible to do it.

So I guess you'll have to save it with a different name.

EDIT: unless you are the person that has the file open. If you open the file via VBA code, just workbookname.save should work

You can overwrite a file that is open in read only mode. To achieve this you need to set the file's attributes to be read only (thus forcing everyone, who's opening it to have it open in read only mode).

This can be done either within the Windows OS (change the file's properties), or through VBA using the SetAttr function https://www.techonthenet.com/excel/formulas/setattr.php

From my own experimentation I reached the following code, which you can use as an example. Assuming you're attempting to save a copy of the currently open workbook to strFileLocation , which is a string variable holding the output file's path, where the file may or may not already exist:

' Verify that the file exists.
If Dir(strFileLocation) <> vbNullString Then
    ' For some reason the read only flag needs to be removed for VBA to be able to overwrite the file.
    SetAttr strFileLocation, vbNormal
End If
' Do the actual (over)writing
ThisWorkbook.SaveCopyAs strFileLocation
' Set the read only flag once more
SetAttr strFileLocation, vbReadOnly

```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM