简体   繁体   English

打开Excel工作簿时将其覆盖-VBA代码

[英]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. 这是Windows的限制,据我所知是不可能的。

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 如果您通过VBA代码打开文件,则仅workbookname.save应该起作用

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 可以在Windows操作系统内(更改文件的属性),也可以使用SetAttr函数https://www.techonthenet.com/excel/formulas/setattr.php通过VBA完成此SetAttr

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: 假设您尝试将当前打开的工作簿的副本保存到strFileLocation ,这是一个字符串变量,用于保存输出文件的路径,该文件可能存在或可能不存在:

' 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

``` ```

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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