用名字移动文件会导致错误5,无效的过程调用或参数

看来我的硬盘本身有一些问题。 这很奇怪。 有些文件出现重复,我删除重复。 几分钟后,我刷新目录,他们回来了。 再次刷新,他们走了。 文件在一台计算机上可见,但不在另一台上。 我会尽力排除麻烦,看看问题出在哪里。 感谢所有帮助到目前为止,可能不止一个问题一起行事。

我已经使用此代码重命名和移动文件从一个位置到另一个在我的networking驱动器上。

video文件被命名为00001,00002等。由于计数器重置,我需要重命名文件的东西,可以在硬盘上工作。

所以所有文件都被重命名为<date> <time>.MTS

这个代码曾经工作,但现在只是因为某种原因停滞了工作。

 Sub MoveFiles() Dim r As Integer r = 2 'first line of files Set objFSO = CreateObject("Scripting.FileSystemObject") Do Until IsEmpty(Cells(r, "A")) Or IsEmpty(Cells(r, "B")) dirPath = Cells(r, "C") + "\" + Cells(r, "B") If objFSO.FileExists(dirPath) Then ' file exist output error message MsgBox ("Filen finns redan!!! " + Cells(r, "A") + " " + Cells(r, "B")) Else FromName = ActiveWorkbook.Path + "\" + Cells(r, "A") ToName = Cells(r, "C") + "\" + Cells(r, "B") ' none of the methods below work. Name FromName As ToName Name ActiveWorkbook.Path + "\" + Cells(r, "A") As Cells(r, "C") + "\" + Cells(r, "B") End If r = r + 1 Loop End Sub 

在这里输入图像说明

由于代码不会创buildToName存在的错误消息,因此它不是“重复”问题。
如果我运行下面的代码

 If objFSO.FileExists(ActiveWorkbook.Path + "\" + Cells(r, "A")) Then MsgBox "test" End If 

我得到消息框,这意味着FromName文件exsists。

所以简而言之,文件存在,并且它将变成的文件名不存在。 还有path(目录),因为它们是在较早的sub()中创​​build的。 我已经加倍检查了。 那么问题是什么?
我完全迷失在这里。

编辑; 添加了工作簿图片:
在这里输入图像说明

这应该做(未testing – YMMV):

 Option Explicit Sub MoveFiles() Dim rownum As Long rownum = 2 'first line of files Dim objFSO As Object ' Required because of Option Explicit Set objFSO = CreateObject("Scripting.FileSystemObject") Dim FromName as String Dim ToName as String Do Until IsEmpty(Cells(rownum, "A")) Or IsEmpty(Cells(rownum, "B")) or rownum > 1048576 ToName = CStr(Cells(rownum, "C")) + "\" + CStr(Cells(rownum, "B")) If objFSO.FileExists(ToName) Then ' file exist output error message MsgBox ("Filen finns redan!!! " + Cells(rownum, "A") + " " + Cells(rownum, "B")) Else FromName = ActiveWorkbook.Path + "\" + CStr(Cells(rownum, "A")) ' none of the methods below work. '' Name FromName As ToName '' Name ActiveWorkbook.Path + "\" + Cells(rownum, "A") As Cells(rownum, "C") + "\" + Cells(rownum, "B") objFSO.MoveFile FromName, ToName End If rownum = rownum + 1 Loop End Sub 

一些事情改变了:

  • Option Explicit :总是在每个VBA文件的顶部使用它。
  • 切勿使用Integer – 使用Long Integer
  • 使用Option Explicit ,你必须为每个variables都有Dim语句。 这样可以防止由于variables名称中的拼写错误而意外创build新variables。
  • Do循环中,在rownum上包含一个完整性检查,这样就不会尝试访问一个不存在的行。
  • 只分配ToName一次,并保存其值。
  • 使用FileSystemObject.MoveFile进行重命名。
  • 使用CStr()来确保你从Cells()得到的值是一个String 。 这将减less由于意想不到的input数据而导致的令人不快的意外风险。

这个问题不是一个确切的重复,但也可能有一些有用的信息。