【问题标题】:VBA: Saving without overwriting existing filesVBA:保存而不覆盖现有文件
【发布时间】: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

【问题讨论】:

标签: vba excel


【解决方案1】:

建议对这么多版本使用日期和时间戳。

“V”和格式(日期,“yyyymmdd”)和格式(时间,“hhmmss”)和“.xlsx”

是的,您可能仍想检查现有文件,但用户很少会在不到一秒的时间内提交输入

【讨论】:

    【解决方案2】:

    遍历各种 _Vn.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 会更好,以便按名称排序的文件夹将它们按正确的顺序排列。

    【讨论】:

    • 感谢@Jeeped,我已经用您的代码 sn-p 更新了我的代码,并添加了其中的“关闭工作簿”部分 - 但我收到一条错误消息 - “next without for”。 ..
    • 我已经开始工作了。但我不得不删除“如果 i > 9 then..”部分。我不确定它为什么会导致这个问题。
    • 如果你遍历所有 i(1 到 9)而没有找到要保存的版本,那么当它退出循环时 i 是 10。这意味着已经创建了所有可能的版本。我不确定是什么问题。
    猜你喜欢
    • 2019-10-10
    • 2018-08-22
    • 2018-02-18
    • 2019-06-04
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多