[英]Function in Excel VBA needs to refresh automatically when workbook is opened
[英]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.