Moving files to another directory

老子叫甜甜 提交于 2021-02-11 17:19:45

问题


I am trying to move several thousand documents from a list in one column and then move them to the folders listed in the other column, and then finally a third column with what has been moved and what hasn't (there will be errors where the file doesn't exist.

I know how to do it on a file by file basis as below:

How do I do it for the whole columns though?

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

回答1:


If these 3 columns are columns "A", "B" and "C", this code should probably work.

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




回答2:


Try this code, please...

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


来源:https://stackoverflow.com/questions/60375463/moving-files-to-another-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!