如果存在文件创建一个具有版本号的新文件

发布于 2025-01-28 04:39:02 字数 772 浏览 2 评论 0原文

我正在尝试检查是否存在具有给定名称的文件,并且它是否确实创建了一个新的名称,该名称结束V2,然后是V3等。

Sub checkFileExists()

    Dim strFileExists, strFileName As String
    Dim nextDay as Date
    Dim i As Integer
    
    strFileName = file_name
    strFileExists = Dir(strFileName)

    If strFileExists = vbNullString Then
        strFileName = file_name
    Else
        i = 1
        Do
            i = i + 1
            strFileName = file_name & "_v" & i
            strFileExists = Dir(strFileName)
        Loop Until strFileExists = vbNullString

        strFileName = file_name & "_v" & i
    End If
 
End Sub

上面的代码几乎总是创建文件名,即使此文件已经退出。

strFileName = "Plan_" & Format(nextDay, "yyyy-mm-dd")

I am trying to check if a file with a given name exists and if it does create a new one with name that ends v2, then v3 and so on.

Sub checkFileExists()

    Dim strFileExists, strFileName As String
    Dim nextDay as Date
    Dim i As Integer
    
    strFileName = file_name
    strFileExists = Dir(strFileName)

    If strFileExists = vbNullString Then
        strFileName = file_name
    Else
        i = 1
        Do
            i = i + 1
            strFileName = file_name & "_v" & i
            strFileExists = Dir(strFileName)
        Loop Until strFileExists = vbNullString

        strFileName = file_name & "_v" & i
    End If
 
End Sub

Above code create almost always file name even if this file already exits.

strFileName = "Plan_" & Format(nextDay, "yyyy-mm-dd")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流云如水 2025-02-04 04:39:02

此功能将返回下一个未使用的文件名版本:

Function GetNextUnUsedVersionName(FilePath As String, Optional hasExtension As Boolean = True)
    Dim Result As String
    Dim Extension As String
    If (hasExtension) Then Extension = Mid(FilePath, InStrRev(FilePath, "."))
    Result = FilePath
    If Len(Dir(Result)) > 0 Then
        Dim n As Long
        n = 1

        Do
            n = n + 1
            Result = Left(FilePath, Len(FilePath) - Len(Extension)) & "_v" & n & Extension
            DoEvents
        Loop Until Len(Dir(Result)) = 0
    End If
    
    GetNextUnUsedVersionName = Result
End Function

This function will return the next unused filename version:

Function GetNextUnUsedVersionName(FilePath As String, Optional hasExtension As Boolean = True)
    Dim Result As String
    Dim Extension As String
    If (hasExtension) Then Extension = Mid(FilePath, InStrRev(FilePath, "."))
    Result = FilePath
    If Len(Dir(Result)) > 0 Then
        Dim n As Long
        n = 1

        Do
            n = n + 1
            Result = Left(FilePath, Len(FilePath) - Len(Extension)) & "_v" & n & Extension
            DoEvents
        Loop Until Len(Dir(Result)) = 0
    End If
    
    GetNextUnUsedVersionName = Result
End Function
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文