首页 > 解决方案 > 使用文件名中的文本作为变量将文件 FromPath 复制到文件夹以确定 ToPath 位置

问题描述

我想将一个主文件夹中的 pdf 文件复制到其他几个位置。

该宏有一段需要根据文件名中的状态缩写将文件复制到三个不同的文件夹中。

如何一次列出多个州的缩写并移动这些文件。

Sub Copy_Certain_Files_In_Folder()

    Dim FSO As Object
    Dim FromPath As String
    Dim ToPath As String
    Dim FileName As String

    FromPath = "C:\Users\Name\Desktop\Master File"  '<< Change
    ToPath = "C:\Users\Name\Desktop\SharePoint\Main"    '<< Change

    FileName = "DOC-AZ*" Or "DOC-CA*" Or "DOC-CO*" Or "DOC-NM*"

    If Right(FromPath, 1) <> "\" Then
        FromPath = FromPath & "\"
    End If

    Set FSO = CreateObject("scripting.filesystemobject")

    If FSO.FolderExists(FromPath) = False Then
        MsgBox FromPath & " doesn't exist"
        Exit Sub
        End If

    If FSO.FolderExists(ToPath) = False Then
        MsgBox ToPath & " doesn't exist"
        Exit Sub
    End If

    FSO.CopyFile Source:=FromPath & FileName, Destination:=ToPath

    MsgBox "You can find the files from " & FromPath & " in " & ToPath

End Sub

标签: excelvba

解决方案


我认为您不能在您的情况下使用通配符副本。如果您首先将 FL、AZ、CA、CO 和 MN 复制到它们的位置,它们将被再次复制,因为您不能为所有其余部分设置负通配符。换一种说法 - FL 也将成为所有其余部分的一部分。如果你移动它,它会起作用的。
现在,您无法使用 FSO 构建那种通配符。相反,您必须一次处理一个,如下所示(稍微简化):

Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim FileName As String

FromPath = "C:\Users\Name\Desktop\Master File"
Set FSO = CreateObject("Scripting.FileSystemObject")

For Each File In FSO.GetFolder(FromPath).Files

    Select Case Mid(File.Name, 5, 2)
        Case "FL"
            ToPath = "FL"
        Case "AZ", "CA", "CO", "NM"
            ToPath = "Main"
        Case Else
            ToPath = "Secondary"
    End Select
    ToPath = "C:\Users\Name\Desktop\SharePoint\" & ToPath

    FSO.CopyFile FromPath & "\" & File.Name, ToPath
Next

Select Case语句选择字母 5-6 并检查。对于您的情况,这可能太具体了,但我认为您明白了。


推荐阅读