我正在尝试将 Excel 工作簿从文件夹 X 复制到文件夹 Y,并且如果文件夹 Y 中已经存在该名称的文件,则该文件不会被覆盖,而是新文件的后缀为“-复制” , '- Copy (2)' 等 - 本质上是重新创建用于在文件夹中复制和粘贴相同文件的手动过程。
我原以为会有一个功能可以让你这样做,但到目前为止我没有尝试过似乎符合确切要求:
Workbook.SaveAs
提示用户是否应替换文件的消息Workbook.SaveCopyAs
只是在没有提示的情况下覆盖文件FileSystemObject.CopyFile
方法有一个 'overwrite' 参数,但是如果设置为 false 并且文件已经存在,这只是错误,这是根据 Microsoft website 的预期行为创建一个根据所选文件夹(.xls (1)、.xls (2) 等)中现有文件的数量递增的计数器并不难,但我希望可能有比这更直接的方法这个。
最佳答案
该功能对我有用,但经过两个步骤。
步骤1 :
进入 VBE 的菜单(工具 -> 引用),然后在“Microsoft Scripting Run-time”旁边打勾。
第2步 :
编辑代码,
因为它是 :
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
我猜你必须在循环中插入一行来更新新文件名,以便检查是否存在。
所以新的代码应该是:
Do
blnNotFound = FileExists(strNewFileName)
If blnNotFound Then intCounter = intCounter + 1
' HERE :
strNewFileName = fl.ParentFolder & "\" & strFileNameNoExt & " (" & intCounter & ")." & strExtension
Loop Until Not blnNotFound
干得好,谢谢。
关于vba - 保存现有 Excel 工作簿的副本而不覆盖它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585931/