知道在文本框中输入的文件名,将文件从一个文件夹复制到另一个文件夹

问题描述 投票:0回答:1

我正在尝试创建一个代码来将 pdf 文件从一个文件夹复制到另一个保持相同名称和所有内容的文件夹。 当我在文本框中键入文件名并单击按钮时,我希望代码将该文件从一个文件夹复制到另一个文件夹。

我的代码正在将源文件夹中的所有文件复制到目标文件夹,并通过我输入的文本框名称 (txtledger.value) 和文件原始名称对其进行重命名。我不知道如何解决它。

Sub CreatingFSO()
Dim MyFSO As FileSystemObject
Set MyFSO = New FileSystemObject
End Sub

Sub CopyFiles()
Dim MyFSO As FileSystemObject
Dim MyFile As File
Dim SourceFolder As String
Dim DestinationFolder As String
Dim MyFolder As Folder

Set MyFile = txtLedger.Value

SourceFolder = "F:\4-2022"
DestinationFolder = "F:\DELEGATION APPLICATION\" & MyFile



Set MyFSO = New Scripting.FileSystemObject
Set MyFolder = MyFSO.GetFolder(SourceFolder)

For Each MyFile In MyFolder.Files
    MyFSO.CopyFile Source:=MyFSO.GetFile(MyFile), _
    Destination:=DestinationFolder & MyFile.Name, Overwritefiles:=False
Next MyFile

End Sub

我是新手,所以我不知道该怎么做。有什么帮助吗?

excel vba excel-formula vba7 vba6
1个回答
0
投票

你可以尝试这样的事情。它将获取您的文本框值,检查该文件是否存在,如果存在则将其复制过来。根据您要执行的操作,如果源 PDF 可能发生更改或类似情况,您可以让它覆盖它。

Sub CopyFile()
    Dim MyFSO As FileSystemObject
    Dim SourceFolder As String
    Dim DestinationFolder As String
    Dim SourceFile As File
    Dim DestinationFile As String
    Dim FileName As String
    
    SourceFolder = "F:\4-2022"
    DestinationFolder = "F:\DELEGATION APPLICATION\"
    
    ' Get the filename from the textbox on the form
    FileName = frmDELEGATION.txtLedger.Value
    ' Or: Forms("frmDELEGATION").Controls("txtLedger").Value
    
    ' Check if the source file exists
    If Not FileExists(SourceFolder & "\" & FileName) Then
        MsgBox "The specified file does not exist."
        Exit Sub
    End If
    
    Set MyFSO = New FileSystemObject
    Set SourceFile = MyFSO.GetFile(SourceFolder & "\" & FileName)
    
    ' Construct the destination file path with the same name
    DestinationFile = DestinationFolder & SourceFile.Name
    
    ' Copy the file to the destination folder
    MyFSO.CopyFile Source:=SourceFile.Path, Destination:=DestinationFile, OverwriteFiles:=False
    
    MsgBox "File copied successfully."
End Sub

Function FileExists(ByVal FilePath As String) As Boolean
    FileExists = (Dir(FilePath) <> "")
End Function

说明:

  • 单击按钮时调用 CopyFile 子例程。
  • 它检查指定的文件是否存在于源文件夹中使用 FileExists 函数。
  • 如果文件不存在,则显示错误信息并退出 子程序。
  • 如果文件存在,它会创建一个 FileSystemObject 的实例。 它检索指定源文件的文件对象。
  • 目标文件路径是通过追加源文件构建的 名称到目标文件夹路径。
  • 最后使用CopyFile方法将文件复制到 目标文件夹,并显示一条成功消息。

**更新以将表单值添加到变量

© www.soinside.com 2019 - 2024. All rights reserved.