繁体   English   中英

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

[英]Overwrite an excel workbook when it is opened -VBA code

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

我认为您无法覆盖打开的文件。 这是Windows的限制,据我所知是不可能的。

因此,我想您必须使用其他名称保存它。

编辑:除非您是已打开文件的人。 如果您通过VBA代码打开文件,则仅workbookname.save应该起作用

您可以覆盖以只读模式打开的文件。 为此,您需要将文件的属性设置为只读(因此,将强制打开文件的所有人将其设置为只读模式)。

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

通过我自己的实验,我到达了以下代码,您可以将其用作示例。 假设您尝试将当前打开的工作簿的副本保存到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