vba将所有docx extn文件从文件夹移动到另一个

时间:2018-10-16 16:33:39

标签: excel vba

请帮助。

我在下面的代码中将文件从一个文件夹移动到另一个文件夹。 但是如果源文件夹中没有文件,则会收到错误消息“找不到文件”。

如果源文件夹中不存在文件,如何更改代码以继续执行而不引发该错误。 还要在源文件夹中移动所有扩展名为。* docx的文件。

Sub move_files()
Name "D:\cashflow\WIP\quarter1\Q1.docx" As "D:\cashflow\CPL\quarter1\backup\Q1.docx"
Name "D:\cashflow\WIP\quarter2\Q2.docx" As "D:\cashflow\CPL\quarter2\backup\Q2.docx"
Name "D:\cashflow\WIP\quarter3\Q3.docx" As "D:\cashflow\CPL\quarter3\backup\Q3.docx"

结束子

4 个答案:

答案 0 :(得分:1)

我确定这是可行的(我已经对其进行了测试)(我将答案放在此处以赚取积分)

Sub List_All_The_Files_Within_Path()

Dim File_Path As String
Dim File_Path2 As String
Dim str As String


File_Path = "D:\cashflow\WIP\quarter3"
File_Path2 = "D:\cashflow\WIP\quarter3\backup"

str = Dir(File_Path & "\*docx")

Do While str <> ""
Name File_Path & "\" & str As File_Path2 & "\" & str
str = Dir()
Loop

MsgBox "success"

End Sub

最好的是,如果找不到任何.docx文件,它就不会出错

答案 1 :(得分:0)

您可以使用

错误恢复下一个

'...得到错误的代码

出错时转到0

此主题很好地解释了这一论点。

vba - how to force ignore/continue past 1004 error

答案 2 :(得分:0)

好吧,对于错误部分,编写起来很简单

On Error Resume Next

在子程序的开头

仅获取文件.docx,这取决于您正在处理的SO。请记住,Windows的VBA与Mac有所不同,这是您可以使用的Windows代码(我尚未尝试过)

Sub List_All_The_Files_Within_Path()


Dim No_Of_Files As Integer    
Dim File_Path1 As String
Dim File_Path2 As String    

File_Path = "D:\cashflow\WIP\quarter3"
File_Path2 = "D:\cashflow\WIP\quarter3\backup"



'Lists all the files in the current directory

With Application.FileSearch
.NewSearch
.LookIn = File_Path
.Filename = "*.docx"
.SearchSubFolders = False
.Execute

No_Of_Files = .FoundFiles.Count

For i = 1 To No_Of_Files
   Name File_Path &.FoundFiles(i).Name  As File_Path2 &.FoundFiles(i).Name

Next i

End With

End Sub

尝试一下,告诉我它是否有效

答案 3 :(得分:0)

测试以查看源文件是否存在,如果存在则将其移动...

Sub move_files()
    MoveIfExists "D:\cashflow\WIP\quarter1\Q1.docx", "D:\cashflow\CPL\quarter1\backup\Q1.docx"
    MoveIfExists "D:\cashflow\WIP\quarter2\Q2.docx", "D:\cashflow\CPL\quarter2\backup\Q2.docx"
    MoveIfExists "D:\cashflow\WIP\quarter3\Q3.docx", "D:\cashflow\CPL\quarter3\backup\Q3.docx"
End Sub

Sub MoveIfExists(src as string, dest as string)
    If Len(Dir(src)) > 0 Then
        Name src As dest
    End If
End sub