【发布时间】:2019-02-28 17:49:38
【问题描述】:
如何确保我的 VBA 代码在保存时不会覆盖现有文件?
示例:我将每张工作表保存为新工作簿,并希望拥有 v1、v2、v3 等。使用下面的代码,我总是覆盖现有文件,就像每个文件一样我保存的文件名相同,以“_V1”结尾...
NewWbName = Left(wbSource.Name, InStr(wbSource.Name, ".") - 1)
For i = 1 To 9
'check for existence of proposed filename
If Len(Dir(wbSource.Path & Application.PathSeparator & NewWbName & "_V" & i & ".xlsx")) = 0 Then
wbTemplate.SaveAs wbSource.Path & Application.PathSeparator & NewWbName & "_V" & i & ".xlsx"
Exit For
End If
Next i
If i > 9 Then
'_V1.xlsx through _V9.xlsx already used; deal with this situation
MsgBox "out of options"
wbTemplate.Close False 'close template
Next wsSource
wbSource.Close False 'close source
End If
End Sub
【问题讨论】:
-
首先检查文件是否存在,例如stackoverflow.com/questions/16351249/vba-check-if-file-exists SO上有很多这样的例子。如果它已经存在,那么您需要决定要做什么......例如重命名或添加数字版本等。