如何确保我的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
答案 0 :(得分:3)
浏览各种_V n .xlsx变体,直到找到一个不存在的变体。
dim i as long, NewWbName as string
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"
end if
如果要将循环数提高到两位数,也许... & "_V" & Format(i, "00") & ".xlsx
会更好,以便按名称排序的文件夹将它们以正确的顺序放置。
答案 1 :(得分:0)
对于许多版本,建议使用日期和时间戳记。
“ V”和格式(日期,“ yyyymmdd”)和格式(时间,“ hhmmss”)和“ .xlsx”
是的,您可能仍要检查现有文件,但是很少用户会在不到一秒钟的时间内提交输入