gpt4 book ai didi

vba - 如何使用 FileSystemObject 到 "Copy and rename"

转载 作者:行者123 更新时间:2023-12-02 08:38:23 25 4
gpt4 key购买 nike

使用 FileSystemObject在 VB/VBA(或 native VBA 调用,我猜)中,我如何:

  1. 复制文件夹
  2. 重命名文件夹

所以,像这样:

mFSO.CopyAndRename(targetFolder, copyDirectory, copyFolderName)

我基本上自己完成了这个,但我更喜欢更干净的方法调用,例如上面的方法(和 CopyFolder 方法)。这似乎有很多代码和很多潜在的故障点......

'
''requires reference to Microsoft Scripting Runtime


Public Function CopyDirectory(ByVal p_copyDirectory As String, p_targetDirectory As String, Optional p_newName As String = "") As Boolean
CopyDirectory = False
Dim m_fso
Set m_fso = New FileSystemObject

Dim mFolder, mNewFolder

If Not Me.DoesPathExist(p_copyDirectory) Then
Exit Function
Else

On Error GoTo errHandler
Set mFolder = m_fso.GetFolder(p_copyDirectory)
mFolder.Copy p_targetDirectory, False

'rename if a "rename" arg is passed
If p_newName <> "" Then
If DoesPathExist(p_targetDirectory & mFolder.Name) Then
Set mNewFolder = m_fso.GetFolder(p_targetDirectory & mFolder.Name)
mNewFolder.Name = "test" & CStr(Rnd(9999))
Else
End If
End If

CopyDirectory = True
On Error GoTo 0

Exit Function
End If

errHandler:
Exit Function

End Function

最佳答案

实际上在 Scripting.FileSystemObject 上有一个名为 CopyFolder 的方法。它可用于一步完成复制和重命名,如下所示:

Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.copyFolder "C:\Path\to\source\folder", "C:\Path\to\destination\folder" true

我在这里找到了代码:http://vba-tutorial.com/copy-a-folder-and-all-of-its-contents/

希望这能回答您的问题。

关于vba - 如何使用 FileSystemObject 到 "Copy and rename",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18966991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com