在工作中,经常会碰到从一堆腐朽的source中按照一个列表去筛选出来现在还要用的source文件。
这个如果用vba来实现的话,会节省大量的时间,而且不会出错。
前提说明:
将想要复制的文件名列表放在第一sheet的第一列,然后执行程序
首先选择源目录和目标目录, 然后会从源目录中查找文件,将存在的文件自动复制的目标目录中,
不存在的文件,记录在第二列里。
Sub fileFilter()Dim folderOld As StringDim folderNew As StringDim fileNm As StringDim fileNmOld As StringDim fileNmNew As StringDim i As IntegerDim j As Integerj = 2MsgBox "Set before moving folder"With Application.FileDialog(msoFileDialogFolderPicker)If .Show = -1 ThenfolderOld = .SelectedItems(1)End IfEnd WithMsgBox "Set after moving folder"With Application.FileDialog(msoFileDialogFolderPicker)If .Show = -1 ThenfolderNew = .SelectedItems(1)End IfEnd WithFor i = 1 To 1000fileNm = Worksheets(1).Cells(i, 1)If fileNm <> "" ThenfileNmOld = folderOld & "\" & fileNmfileNmNew = folderNew & "\" & fileNmIf Dir(fileNmOld) <> "" ThenFileCopy fileNmOld, fileNmNewElseWorksheets(1).Cells(j, 2) = fileNmj = j + 1End IfEnd IfNextMsgBox "file filter over"End Sub
另外,vba读取文件方法备用
Sub readFile()Dim txtLineDim FileObjDim TextObjDim FilePathWith Application.FileDialog(msoFileDialogFilePicker)If .Show = -1 ThenFilePath = .SelectedItems(1)End IfEnd WithDim txt As StringOpen FilePath For Input As #1Do While Not EOF(1)Line Input #1, txtMsgBox txtLoopClose #1End Sub