我沒有找到任何直接的方法。下面的代碼將給出所需的結果。由於fso對象不適合我,所以稍微修改了之前的帖子。
Public Function CUSTOM_SAVECOPYAS_FILENAME(strFilePath As String) As String
Dim intCounter As Integer
Dim blnNotFound As Boolean
Dim arrSplit As Variant
Dim strNewFileName As String
Dim strFileName As String
Dim strFileNameNoExt As String
Dim strExtension As String
Dim pos As Integer
Dim strFilePathNoFileName As String
arrSplit = Split(strFilePath, "\")
pos = InStrRev(strFilePath, "\")
strFilePathNoFileName = Left(strFilePath, pos)
strFileName = arrSplit(UBound(arrSplit))
strFileNameNoExt = Split(strFileName, ".")(0)
strExtension = Split(strFileName, ".")(1)
intCounter = 1
If FileExists(strFilePath) = True Then
'Set fl = FSO.GetFile(strFilePath)
strNewFileName = strFilePathNoFileName & strFileNameNoExt & " (" & intCounter & ")." & strExtension
Do
blnNotFound = FileExists(strNewFileName)
If blnNotFound Then intCounter = intCounter + 1
Loop Until Not blnNotFound
Else
strNewFileName = strFilePath
End If
'This function will return file path to main function where you save the file
CUSTOM_SAVECOPYAS_FILENAME = strNewFileName
End Function
Public Function FileExists(ByVal path_ As String) As Boolean
FileExists = (Len(Dir(path_)) > 0)
End Function
'main
Sub main()
'.......
str_fileName = "C:/temp/test.xlsx"
str_newFileName = CUSTOM_SAVECOPYAS_FILENAME(str_fileName)
Application.DisplayAlerts = False
NewWb.SaveAs str_newFileName
NewWb.Close
Application.DisplayAlerts = True
End Sub
在這裏與你的直覺。 IMO最好的解決辦法是在這裏設置自己的櫃檯並更改名稱文件。 (我不知道是否有這個「工作」的vba函數,說實話,如果存在的話我會感到驚訝) – Blenikos
使用FileSystemObject File.Exists方法,然後使用regex或mid '/'instr'來獲得(x)號碼,如果有一個和增量。 –