VBA: Saving without overwriting existing files

2019-08-02 16:37发布

how can I make sure that my VBA code is not overwriting existing files while saving?

Example: I'm saving every sheet as a new workbook, and want to have v1, v2, v3 etc. With the code below I'm always overwriting the existing file, as every file I save has the same file name with "_V1" ending...

    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

2条回答
一纸荒年 Trace。
2楼-- · 2019-08-02 17:25

Loop through various _Vn.xlsx variations until you find one that isn't there.

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

If you are going to raise the loop into double digits, perhaps ... & "_V" & Format(i, "00") & ".xlsx would be better so that a folder sorted by name puts them in the correct order.

查看更多
孤傲高冷的网名
3楼-- · 2019-08-02 17:26

Recommend using a date and time stamp for so many versions.

“V” & Format(date, “yyyymmdd”) & format(time, “hhmmss”) & “.xlsx”

Yes, you may still want to check for an existing file, but it’s seldom the user will submit input in less than a second

查看更多
登录 后发表回答