将文件移动到另一个目录

时间:2020-02-24 11:58:01

标签: excel vba file directory move

我试图将一列中的几千个文档移到另一列中,然后将它们移到另一列中列出的文件夹中,最后再移至第三列,其中包含已移动内容和未移动内容(会有文件不存在的错误。

我知道如何逐个文件地进行操作,如下所示:

enter image description here

但是如何为整个专栏做这件事?

Sub Copy_One_File()
  FileCopy "C:\Users\Ron\SourceFolder\Test.xls", "C:\Users\Ron\DestFolder\Test.xls"
End Sub

Sub Move_Rename_One_File()
  'You can change the path and file name
  Name "C:\Users\Ron\SourceFolder\Test.xls" As "C:\Users\Ron\DestFolder\TestNew.xls"
End Sub

2 个答案:

答案 0 :(得分:1)

如果这3列是“ A”,“ B”和“ C”列,则此代码可能应该起作用。

Sub move_files()
  Dim i As Long
  With ActiveSheet
    For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
      Err.Clear
      On Error Resume Next
      Name (.Cells(i, 1)) As .Cells(i, 2) & "\" & StrReverse(Split(StrReverse(.Cells(i, 1)), "\")(0))
      If Err = 0 Then .Cells(i, 3) = "YES" Else .Cells(i, 3) = "NO"
      On Error GoTo 0
    Next
  End With
End Sub

答案 1 :(得分:0)

请尝试此代码...

Sub testCopyFiles()
 Dim sh As Worksheet, lastRow As Long, i As Long, destPath As String
 Dim fN As String, fileName As String
 Set sh = ActiveSheet
 lastRow = sh.Range("A" & Cells.Rows.count).End(xlUp).row

 For i = 2 To lastRow
    fN = sh.Range("A" & i).Value
    destPath = sh.Range("B" & i).Value & "\" & _
                Right(fN, Len(fN) - InStrRev(fN, "\"))
    FileCopy sh.Range("A" & i).Value, destPath
    sh.Range("C" & i).Value = "Yes"
 Next i
End Sub