如果文件已存在于目录中,请使用其他名称保存

时间:2015-07-29 14:34:07

标签: excel vba excel-vba

我不知道这段代码我错在哪里。

  ##code  
for s=10:10:100
  'my code for make a specific scope from raw data'
  ...
% result is the storage space
numData=size('from the scope');
result=zeros(numData,25); 
%calculate within the scope
  for i=1:numData
  data_new_x = Scope(:,i);
  data_mean_x=mean(data_new_x); %mean x
  result(i,1)=data_mean_x;
  ...
  end
end

一切正常,但是当我在列中遇到相同的值时(例如:John Doe,John Doe),程序会覆盖第一个John Doe文件。

6 个答案:

答案 0 :(得分:3)

这是一个可用于检索任何给定路径的唯一文件名的函数。它将使用" - n"为文件名后缀,其中n是序号。

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存在,则进行以下调用:

Debug.Print GetNextAvailableName("c:\path\to\file.ext")

会打印:

c:\path\to\file - 1.ext

答案 1 :(得分:0)

If FileLen(FILE_PATH & personList(i, 1) & FILE_EXT) > 0 Then
    '// File Exists, change name accordingly.
Else
    '// File doesn't exist, save as is.
End If

答案 2 :(得分:0)

以下是创建唯一文件路径(taken from http://mielk.pl/)的功能:

Public Function uniqueFilePath(filepath As String) As String
    Const METHOD_NAME As String = "uniqueFilePath"
    '------------------------------------------------------------------------------------------------------
    Static objFSO As Object                 '(Late binding that allows to use the function, even if
                                            'Microsoft Scripting Runtime library is not loaded)
    Dim strFileExtension As String
    Dim strFileName As String
    Dim strParentFolder As String
    Dim strTempFilePath As String
    Dim intCounter As Integer
    '------------------------------------------------------------------------------------------------------



    'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------|
    If objFSO Is Nothing Then                                                                           '|
        Set objFSO = VBA.CreateObject("Scripting.FileSystemObject")                                     '|
    End If                                                                                              '|
    '----------------------------------------------------------------------------------------------------|


    With objFSO

        'Checks if the file already exists. -------------------------------------------------------------|
        If .fileExists(filepath) Then                                                                   '|
                                                                                                        '|
            'If the given filepath already exists, function transforms its name by                      '|
            'appending the number in brackets.                                                          '|
            strParentFolder = .GetParentFolderName(filepath)                                            '|
            If Not VBA.right$(strParentFolder, 1) = "\" Then strParentFolder = strParentFolder & "\"    '|
            strFileName = .GetBaseName(filepath)                                                        '|
            strFileExtension = "." & .GetExtensionName(filepath)                                        '|
                                                                                                        '|
            '------------------------------------------------------------------------------------|      '|
            Do                                                                                  '|      '|
                intCounter = intCounter + 1                                                     '|      '|
                strTempFilePath = strParentFolder & strFileName & _
                                                " (" & intCounter & ")" & strFileExtension      '|      '|
            Loop While .fileExists(strTempFilePath)                                             '|      '|
            '------------------------------------------------------------------------------------|      '|
                                                                                                        '|
            uniqueFilePath = strTempFilePath                                                            '|
                                                                                                        '|
        Else                                                                                            '|
                                                                                                        '|
            'Specified filepath is unique in the file system and is returned in its original form.      '|
            uniqueFilePath = filepath                                                                   '|
                                                                                                        '|
        End If                                                                                          '|
        '-------- [If .FileExists(filepath) Then] -------------------------------------------------------|

    End With


End Function

为了使下面的代码正常工作,您必须将其粘贴到代码中。

如果您作为参数提供的文件路径已存在,函数将返回相同的文件路径,并附加括号中的数字,即如果文件“C:\ file.xlsx”已存在,则函数返回“C” :\ file(1).xlsx“。

如果此文件不存在,函数将返回原始文件路径而不做任何更改。

使用以下内容替换您在问题中粘贴的所有代码:

Dim filepath As String

filepath = uniqueFilePath(FILE_PATH & personList(i, 1) & FILE_EXT)
Call .SaveAs(filepath)
Call .Close

答案 3 :(得分:0)

我使用非常相似的东西来发布文件。可以看看你是否可以根据需要改变它

Rechecker:
Filename = Sheets("Word_Front").Range("N142").Value
If Not (Update_Only) Then
    If Dir(sDocPath & Filename & Cert & ".docx") <> "" Then
        iret = MsgBox("Existing file found with this filename, Answer YES to up-issue the file. Please note there is no further warning and NO to overwrite the file.", vbYesNo)
        If iret = 6 Then
            Sheets("Word_Front").Range("Q7").Value = Sheets("Word_Front").Range("Q7").Value + 1
            GoTo Rechecker
        Else
            oDoc.SaveAs sDocPath & Filename & Cert & ".docx", 16
        End If
    Else
        oDoc.SaveAs sDocPath & Filename & Cert & ".docx", 16
    End If
End If

答案 4 :(得分:0)

我已经把这个功能挂了一个年龄 - 不知道我从哪里得到它。如果文件名没有扩展名,或者有超过100个具有相同基本名称的文件,它将暂停:

Sub test()

    Debug.Print GenerateUniqueName("S:\Bartrup-CookD\New Folder\Book1.xlsm")

End Sub

'----------------------------------------------------------------------
' GenerateUniqueName
'
'   Generates a file name that doesn't exist by appending a number
'   in between the base name and the extension.
'   Example: GenerateUniqueName("c:\folder\file.ext") = "c:\folder\file4.ext"
'----------------------------------------------------------------------
Function GenerateUniqueName(FullFileName As String, Optional fAlwaysAddNumber As Boolean) As String

    Dim objFSO As Object: Set objFSO = CreateObject("Scripting.FileSystemObject")

    If Not objFSO.FileExists(FullFileName) And Not fAlwaysAddNumber Then
        GenerateUniqueName = FullFileName
    Else
        Dim strExt As String
        Dim strNonExt As String
        Dim strNewName As String
        Dim i As Integer
        strExt = objFSO.GetExtensionName(FullFileName)
        Debug.Assert strExt <> ""
        strNonExt = objFSO.BuildPath(objFSO.GetParentFolderName(FullFileName), objFSO.GetBaseName(FullFileName))
        Do
            Debug.Assert i < 100
            i = i + 1
            strNewName = strNonExt & i & "." & strExt

        Loop While objFSO.FileExists(strNewName)
        GenerateUniqueName = strNewName
    End If
End Function

答案 5 :(得分:0)

对于看起来非常简单的问题,很多这些都是非常长的答案。大多数引用FileSystemObject;我注意到你没有参考。

我的解决方案是使用WHILE代替IF

While Dir(FILE_PATH & personList(i, 1) & FILE_EXT) <> ""
    i = i + 1
Wend
.SaveAs2 FILE_PATH & i & "1" & personList(i, 1) & FILE_EXT
.Close

这保留了&#34; 1&#34;当文件尚不存在时,您的初始代码。这也意味着你的列表中可以有几千个重复的名字,因为第一个John Doe的文件将被命名为&#34; 11John Doe&#34;,第二个将是&#34; 21John Doe&#34然后&#34; 31John Doe&#34;等等。更轻松的代码并没有开始实现新的库。