vba 如何使用 workbook.saveas 自动覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14634453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:52:08  来源:igfitidea点击:

How to use workbook.saveas with automatic Overwrite

excel-vbaexcel-2010vbaexcel

提问by bob.mazzo

In this section of code, Excel ALWAYS prompts: "File already exists, do you want to overwrite?"

这一段代码中,Excel总是提示:“文件已经存在,要覆盖吗?”

Application.DisplayAlerts = False
Set xls = CreateObject("Excel.Application")
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"

wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=True   

wb.Close(True)

Why does db.SaveAsalways prompt me to overwrite existing file if I have DisplayAlerts = False?

db.SaveAs如果我有,为什么总是提示我覆盖现有文件DisplayAlerts = False

Thanks in advance!

提前致谢!

回答by Sorceri

To hide the prompt set xls.DisplayAlerts = False

隐藏提示集 xls.DisplayAlerts = False

ConflictResolutionis not a trueor falseproperty, it should be xlLocalSessionChanges

ConflictResolution不是一个truefalse属性,它应该是xlLocalSessionChanges

Notethat this has nothing to do with displaying the Overwrite prompt though!

请注意,这与显示覆盖提示无关!

Set xls = CreateObject("Excel.Application")    
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"

wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges    
wb.Close (True)

回答by Uttam

I recommend that before executing SaveAs, delete the file it exists.

我建议在执行 SaveAs 之前,删除它存在的文件。

If Dir("f:ull\path\with\filename.xls") <> "" Then
    Kill "f:ull\path\with\filename.xls"
End If

It's easier than setting DisplayAlerts off and on, plus if DisplayAlerts remains off due to code crash, it can cause problems if you work with Excel in the same session.

这比关闭和打开 DisplayAlerts 更容易,而且如果 DisplayAlerts 由于代码崩溃而保持关闭,如果您在同一会话中使用 Excel,则可能会导致问题。

回答by Harry S

To split the difference of opinion

分散意见分歧

I prefer:

我更喜欢:

   xls.DisplayAlerts = False    
   wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
   xls.DisplayAlerts = True