VBA使用Excel对象中列出的完整路径和文件名复制文件

时间:2014-07-29 21:07:26

标签: excel file vba excel-vba copy

我正在编写一个需要的宏:

1从该文件夹的特定文件夹和子文件夹中获取文件列表(大约10k行),并将其发布到excel工作簿(Sheet1)中,文件名和扩展名“somefile.ext”在A列中,并在列中填写完整的文件路径C(例如D:\ 2014 \ Client Name \ Misc \ somefile.ext)

2过滤掉符合我要求的文件,并删除不符合要求的行。

3使用C列的完整路径将这些列出的文件复制到新目录中,但保留子文件夹结构,以便:

D:\ 2014 \ Client Name \ Misc \ somefile.ext变为D:\ 2015 \ Client Name \ Misc \ somefile.ext。

如果路径已存在(使用此宏创建)在新文件夹中,但文件不存在。

现在我自己已经达到了#3。我被困在复制这些文件,我只是缺乏技术诀窍。我请你们帮忙。

以下是符合但不包括第3点的代码:

Option Explicit
Sub ListFiles()

Dim objFSO As Scripting.FileSystemObject
Dim objTopFolder As Scripting.folder
Dim strTopFolderName As String

Range("A1").Value = "File Name"
Range("B1").Value = "File Type"
Range("C1").Value = "File Patch"

strTopFolderName = "D:\2014"

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objTopFolder = objFSO.GetFolder(strTopFolderName)

Call RecursiveFolder(objTopFolder, True)

Columns.AutoFit

End Sub

Sub RecursiveFolder(objFolder As Scripting.folder, _
IncludeSubFolders As Boolean)

Dim objFile As Scripting.file
Dim objSubFolder As Scripting.folder
Dim NextRow As Long

NextRow = Cells(Rows.Count, "A").End(xlUp).Row + 1

For Each objFile In objFolder.Files
    Cells(NextRow, "A").Value = objFile.Name
    Cells(NextRow, "B").Value = objFile.Type
    Cells(NextRow, "C").Value = objFile.path
    NextRow = NextRow + 1
Next objFile

If IncludeSubFolders Then
    For Each objSubFolder In objFolder.SubFolders
        Call RecursiveFolder(objSubFolder, True)
    Next objSubFolder
End If
End Sub
Sub delete_rows()

Dim lastrow As Long
Dim row_index As Long

Application.ScreenUpdating = False
lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
For row_index = lastrow - 1 To 1 Step -1
If InStr(Cells(row_index, "A").Value, "Processing") = 0 Then
Cells(row_index, "A").EntireRow.Delete
End If
Next
Columns.AutoFit
Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

我认为这会做你想要的(你可以删除/ K使命令窗口消失)。

  Call Shell("""cmd"" /K copy " & _
    "D:\2014\Client Name\Misc\somefile.ext " & _
    "D:\2015\Client Name\Misc\somefile.ext", vbNormalFocus)
编辑:蒂姆的回答(作为评论)要简单得多。我在想一个"炮轰"命令可以使用通配符,这可能很有用,我不认为你可以使用FileCopy来做到这一点。

FileCopy source, destination
  

来源:必填。字符串表达式,指定的名称   要复制的文件。源可能包括目录或文件夹,以及   驾驶。目的地:必填。字符串表达式,指定   目标文件名。目的地可能包括目录或文件夹,以及   驱动。