如何将excel指定文件夹中的文件移至目标文件夹?

网友投稿 489 2022-10-19

如何将excel指定文件夹中的文件移至目标文件夹?

Q:如下图1所示,在工作表列A中存储着需要移动的文件所在的文件夹路径,列B中是要将文件移到的目标文件夹路径,现在需要将列A中文件夹下的文件移到列B中文件夹内,如何实现?

图1

A:下面使用FileSystemObject对象的MoveFile方法来移动文件:

Sub MoveFilesToNewFolder()

Dim FSO As Object

‘源文件路径

Dim strSourcePath As String

‘目标路径

Dim strTargetPath As String

‘文件类型

Dim strFileExt As String

‘文件名

Dim strFileNames As String

‘最后一行行号

Dim lngLastRow As Long

Dim i As Long

lngLastRow = Cells(Rows.Count,1).End(xlUp).Row

For i = 2 To lngLastRow

strSourcePath = Range(“A”& i).Value

strTargetPath = Range(“B”& i).Value

‘可以修改为你想要移动的文件扩展类型,例如*.docx

strFileExt = “*.*”

If Right(strSourcePath, 1) <>”\” Then

strSourcePath = strSourcePath & “\”

End If

strFileNames = Dir(strSourcePath &strFileExt)

If Len(strFileNames) = 0 Then

MsgBox strSourcePath & “中没有文件.”

End If

Set FSO = CreateObject(“Scripting.FileSystemObject”)

‘目标路径不存在则创建该路径

On Error Resume Next

FSO.CreateFolder (strTargetPath)

‘移动文件

FSO.MoveFile _

Source:=strSourcePath &strFileExt, _

Destination:=strTargetPath

Next i

End Sub

代码中,你可以修改

strFileExt =”*.*”

为你想要移动的文件扩展名,从而实现只移动该类型的文件。

语句:

On Error Resume Next

FSO.CreateFolder(strTargetPath)

在不存在指定名称的文件夹时,将会创建该文件夹。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:excel表格内间距怎么调大
下一篇:甘特图的目的
相关文章