【问题标题】:Moving files to another directory将文件移动到另一个目录
【发布时间】:2020-02-24 11:58:01
【问题描述】:

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

我知道如何逐个文件地执行以下操作:

但是,我如何为整个列执行此操作?

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

【问题讨论】:

  • 你需要一个循环。 (那些不称为超链接,它们只是带有完整路径的文件名)
  • 也许看看FSO文件系统对象,你可以遍历文件夹内容。

标签: excel vba file directory move


【解决方案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

【讨论】:

  • 嗨,谢谢这个作品。非常感激。一个后续问题,如果我想复制文件而不是移动或删除文件,它是一个简单的替代品吗?谢谢,斯科特。
  • 嘿,很高兴为您提供帮助。我没有测试复制部分,但似乎你应该可以通过替换中间行中的东西来做到这一点:NameFileCopyAs,
【解决方案2】:

请试试这个代码...

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

【讨论】:

  • 感谢您的帖子,它在以下位置出现错误:FileCopy sh.Range("A" & i).Value, destPath
  • @Scottyp:我错过了说某些路径可能是错误的部分。该代码可以很容易地用于初步检查文件或文件夹是否存在并返回(在括号中)错误的...或者,只跳过错误并让您直观地检查两个路径中的哪一个是错误的。
猜你喜欢
  • 2017-07-20
  • 2014-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 2014-12-04
  • 2021-11-12
相关资源
最近更新 更多