如果文件已存在于目录中,请使用其他名称保存 [英] Save with a different name if the file already exists in directory
本文介绍了如果文件已存在于目录中,请使用其他名称保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道我在哪里错了这段代码.
I don't know where I am wrong with this code.
If Dir(FILE_PATH & personList(i, 1) & FILE_EXT) <> "" Then
.SaveAs2 FILE_PATH & "1" & personList(i, 1) & FILE_EXT
.Close
Else
.SaveAs2 FILE_PATH & personList(i, 1) & FILE_EXT
.Close
End If
一切正常,但是当我在列中遇到相同的值(例如:John Doe,John Doe)时,程序将覆盖第一个John Doe文件.
Everything just works fine, but when I encounter the same value in a column (for example: John Doe, John Doe), the program overwrites the first John Doe file.
推荐答案
以下是您可以用来为任何给定路径检索唯一文件名的函数.它将在文件名后加上" - n"
,其中n
是序列号.
Here's a function you can use to retrieve a unique file name for any given path. It will suffix the filename with a " - n"
, where n
is a sequential number.
Function GetNextAvailableName(ByVal strPath As String) As String
With CreateObject("Scripting.FileSystemObject")
Dim strFolder As String, strBaseName As String, strExt As String, i As Long
strFolder = .GetParentFolderName(strPath)
strBaseName = .GetBaseName(strPath)
strExt = .GetExtensionName(strPath)
Do While .FileExists(strPath)
i = i + 1
strPath = .BuildPath(strFolder, strBaseName & " - " & i & "." & strExt)
Loop
End With
GetNextAvailableName = strPath
End Function
假设文件c:\path\to\file.ext
存在,则进行以下调用:
Assuming the file c:\path\to\file.ext
exists, the following call:
Debug.Print GetNextAvailableName("c:\path\to\file.ext")
将打印:
c:\path\to\file - 1.ext
这篇关于如果文件已存在于目录中,请使用其他名称保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文