当前位置:首页教育技巧excel技巧excel换行

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

2025-12-09 09:18:09


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

图1

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

Sub MoveFilesToNewFolder()

‘声明FileSystemObject对象

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)

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

相关信息


电脑版

【免责声明】本站信息来自网友投稿及网络整理,内容仅供参考,如果有错误请反馈给我们及时更正,对文中内容的真实性和完整性本站不提供任何保证,不承但任何责任。
版权所有:学窍知识网 Copyright © 2011-2026 www.at317.com All Rights Reserved .