omegastripes

batch_move_rename_excel_assisted_utility.vbs

Aug 9th, 2014
501
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ' Batch move / rename Excel assisted utility.
  2.  
  3. ' The code below is batch move / rename utility. Select files or / and folders in explorer folder or in explorer search results to be renamed / moved and drag onto this script file. Files in subfolders will be included.
  4.  
  5. ' Then source files foldername, filename and extension populates the first 3 columns of created Excel worksheet, and the same values in the next 3 columns for destination files. After making necessary changes to destination columns, confirm in first dialog to start batch. If destination folder(s) doesn't exists - it will be created. All changes can be rolled back by selecting Cancel in second dialog.
  6.  
  7. ' As you know Excel has powerfull tools for text processing, now what you need for batch move / rename is just to replace text in certain cells. Experienced who knows Excel inside out can do that easily. E. g. select entire row with filenames or foldernames, press Ctrl+H and replace some text in all cells. Or enter name with number to the first cell and stretch it  across others to auto-numerate. Therefore few clicks allows to change all filenames and even move files to another folders.
  8.  
  9. Option Explicit
  10. Const xlWBATWorksheet = -4167
  11. Dim oFSO, oChgFiles, oChgFolders, oApp, oWB, oWS,  aFiles(), aCells(), aTask, lRow, sSrc, sDst, sStat, sCmt, sKey, bNotDeleted
  12.  
  13. If WScript.Arguments.Count = 0 then
  14.     CreateObject("WScript.Shell").PopUp "Drag'n'Drop files to batch move / rename", 3, "Batch move / rename", vbInformation
  15.     WScript.Quit
  16. End If
  17.  
  18. Set oFSO = CreateObject("Scripting.FileSystemObject")
  19. Set oChgFiles = CreateObject("Scripting.Dictionary")
  20. Set oChgFolders = CreateObject("Scripting.Dictionary")
  21. Set oApp = CreateObject("Excel.Application")
  22. oApp.Visible = True
  23. Set oWB = oApp.Workbooks.Add(xlWBATWorksheet)
  24. Set oWS = oWB.Worksheets(1)
  25. Redim aFiles(-1)
  26. For Each sSrc In WScript.Arguments
  27.     AddFiles sSrc
  28. Next
  29. If UBound(aFiles) = -1 Then
  30.     CreateObject("WScript.Shell").PopUp "No files selected", 3, "Batch move / rename", vbInformation
  31.     WScript.Quit
  32. End If
  33. ReDim aCells(UBound(aFiles), 5)
  34. For lRow = 0 To UBound(aFiles)
  35.     aCells(lRow, 0) = oFSO.GetParentFolderName(aFiles(lRow))
  36.     aCells(lRow, 1) = oFSO.GetBaseName(aFiles(lRow))
  37.     aCells(lRow, 2) = oFSO.GetExtensionName(aFiles(lRow))
  38.     aCells(lRow, 3) = oFSO.GetParentFolderName(aFiles(lRow))
  39.     aCells(lRow, 4) = oFSO.GetBaseName(aFiles(lRow))
  40.     aCells(lRow, 5) = oFSO.GetExtensionName(aFiles(lRow))
  41. Next
  42. oWS.Range(oWS.Cells(1, 1), oWS.Cells(UBound(aFiles) + 1, 6)).NumberFormat = "@"
  43. oWS.Range(oWS.Cells(1, 1), oWS.Cells(UBound(aFiles) + 1, 6)).Value = aCells
  44. oWS.Columns.AutoFit
  45. oWB.Saved = True
  46.  
  47. If MsgBox("Columns contains:" & vbCrLf & vbCrLf & "Source files:" & vbCrLf & "A - path" & vbCrLf & "B - name" & vbCrLf & "C - ext" & vbCrLf & vbCrLf & "Destination files:" & vbCrLf & "D - path" & vbCrLf & "E - name" & vbCrLf & "F - ext" & vbCrLf & vbCrLf & "Make changes to destination then press OK to batch move / rename", vbOKCancel + vbInformation, "Batch move / rename") = vbOK Then
  48.     sStat = ""
  49.     If ChkWb Then
  50.         aTask = oWS.Range(oWS.Cells(1, 1), oWS.Cells(UBound(aFiles) + 1, 6)).Value
  51.         For lRow = 1 To UBound(aTask) ' used src
  52.             Do ' do loop block used to provide skip the rest with exit do
  53.                 If Not ChkWb Then Exit Do
  54.                 On Error Resume Next
  55.                 If Right(aTask(lRow, 1), 1) <> "\" Then aTask(lRow, 1) = aTask(lRow, 1) & "\"
  56.                 sSrc = aTask(lRow, 1) & aTask(lRow, 2)
  57.                 If aTask(lRow, 3) <> "" Then
  58.                     sSrc = sSrc & "." & aTask(lRow, 3)
  59.                 End If
  60.                 If Not oFSO.FileExists(sSrc) Then
  61.                     sCmt = "Source file doesn't exists"
  62.                     Exit Do
  63.                 End If
  64.                 If Right(aTask(lRow, 4), 1) <> "\" Then aTask(lRow, 4) = aTask(lRow, 4) & "\"
  65.                 sDst = aTask(lRow, 4) & aTask(lRow, 5)
  66.                 If aTask(lRow, 6) <> "" Then
  67.                     sDst = sDst & "." & aTask(lRow, 6)
  68.                 End If
  69.                 If Not ChkWb Then Exit Do
  70.                 If LCase(sSrc) = LCase(sDst) Then
  71.                     sCmt = "Source and destination the same"
  72.                     Exit Do
  73.                 End If
  74.                 sCmt = ""
  75.                 If oChgFiles.Exists(sDst) Then
  76.                     sCmt = "Another destination file with same name has been processed already" ' interrupt if another dst with same name has been processed already
  77.                     Exit Do
  78.                 End If
  79.                 If oFSO.FileExists(sDst) Then ' dst file already exists - need dst backup
  80.                     If oFSO.FileExists(sDst & ".DSTBAK") Then ' old dst backup already exists - need to delete
  81.                         oFSO.DeleteFile sDst & ".DSTBAK", True ' delete old dst backup
  82.                         If IsError("Del prev .DSTBAK", sCmt) Then Exit Do
  83.                     End If
  84.                     oFSO.MoveFile sDst, sDst & ".DSTBAK" ' make dst backup
  85.                     If IsError("Move DST -> .DSTBAK", sCmt) Then Exit Do
  86.                     oChgFiles.Add sDst & ".DSTBAK", sDst ' add data for dst backup to be recovered while rollback actions
  87.                 Else ' dst file hasn't exist yet - not need dst backup
  88.                     ' файла dst нет - здесь нужно проверить наличие папки dst и создать если ее нет, после проверить оибку
  89.                     If Not oFSO.FolderExists(oFSO.GetParentFolderName(sDst)) Then ' dst folder hasn't exist yet - need to create
  90.                         SmartCreateFolder oFSO.GetParentFolderName(sDst) ' create dst folder
  91.                         If IsError("Create DST folder", sCmt) Then Exit Do ' interrupt if error creating dst folder
  92.                     End If
  93.                     oChgFiles.Add sDst, "" ' add data for dst to be deleted while rollback actions
  94.                 End If
  95.                 oFSO.CopyFile sSrc, sDst, True ' copy src to dst
  96.                 If IsError("Copy SRC -> DST", sCmt) Then Exit Do
  97.                 If oFSO.FileExists(sSrc & ".SRCBAK") Then ' old src backup already exists - need to delete
  98.                     oFSO.DeleteFile sSrc & ".SRCBAK", True ' delete old src backup
  99.                     If IsError("Del prev .SRCBAK", sCmt) Then Exit Do
  100.                 End If
  101.                 oFSO.MoveFile sSrc, sSrc & ".SRCBAK" ' make src backup 
  102.                 If IsError("Move SRC -> .SRCBAK", sCmt) Then Exit Do
  103.                 oChgFiles.Add sSrc & ".SRCBAK", sSrc ' add data for src backup to be recovered while rollback actions
  104.                 If Err.Number <> 0 Then Err.Clear
  105.             Loop Until True ' no repeat
  106.             On Error Goto 0
  107.             If sCmt <> "" Then
  108.                 AddMsg sSrc & vbCrLf & sCmt, sStat
  109.                 On Error Resume Next
  110.                 Do
  111.                     Err.Clear
  112.                     oWS.Activate
  113.                     If oWS.Cells(lRow, 1).Comment Is Nothing Then oWS.Cells(lRow, 1).AddComment
  114.                     oWS.Cells(lRow, 1).Comment.Visible = False
  115.                     oWS.Cells(lRow, 1).Comment.Text sCmt
  116.                     oWB.Saved = True
  117.                 Loop While (Err.Number <> 0) And ChkWb
  118.             End If
  119.         Next
  120.         If Not ChkWb Then AddMsg "Batch interrupted due to Excel workbook closed", sStat
  121.         If sStat <> "" Then ShowInNotepad sStat ' show batch errors
  122.         On Error Resume Next
  123.         If oChgFiles.Count > 0 Or oChgFolders.Count > 0 Then
  124.             sStat = ""
  125.             If MsgBox("OK - confirm changes, Cancel - rollback", vbOKCancel + vbQuestion, "Batch move / rename") = vbOK Then
  126.                 If MsgBox("Remove all backup files?", vbOKCancel + vbQuestion, "Batch move / rename") = vbOK Then
  127.                     For Each sKey In oChgFiles
  128.                         If oChgFiles(sKey) <> "" Then
  129.                             oFSO.DeleteFile sKey, True
  130.                             IsError "Delete" & vbCrLf & sKey, sStat
  131.                         End If
  132.                     Next
  133.                 End If
  134.             Else
  135.                 For Each sKey In oChgFiles
  136.                     If oChgFiles(sKey) = "" Then
  137.                         oFSO.DeleteFile sKey, True
  138.                         IsError "Delete" & vbCrLf & sKey, sStat
  139.                     Else
  140.                         If oFSO.FileExists(oChgFiles(sKey)) Then
  141.                             oFSO.DeleteFile oChgFiles(sKey), True
  142.                             IsError "Delete" & vbCrLf & oChgFiles(sKey), sStat
  143.                         End If
  144.                         oFSO.MoveFile sKey, oChgFiles(sKey)
  145.                         IsError sKey & vbCrLf & "Move To" & vbCrLf & oChgFiles(sKey), sStat
  146.                     End If
  147.                 Next
  148.                 Do
  149.                     bNotDeleted = True
  150.                     For Each sKey In oChgFolders ' each created folder
  151.                         If oFSO.FolderExists(sKey) Then
  152.                             With oFSO.GetFolder(sKey)
  153.                                 If (.Files.Count = 0) And (.SubFolders.Count = 0) Then
  154.                                     .Delete True
  155.                                     If Not IsError("Delete" & vbCrLf & sKey, sStat) Then bNotDeleted = False
  156.                                 End If
  157.                             End With
  158.                         End If
  159.                     Next
  160.                 Loop Until bNotDeleted ' untill no changes pass
  161.             End If
  162.             On Error Goto 0
  163.             If sStat <> "" Then ShowInNotepad sStat ' show rollback errors
  164.         Else
  165.             CreateObject("WScript.Shell").PopUp "No changes made", 3, "Batch move / rename", vbInformation
  166.             On Error Goto 0
  167.         End If
  168.     End If
  169. End if
  170. If ChkWb Then
  171.     oWB.Saved = True
  172.     If CreateObject("WScript.Shell").PopUp("Close Excel?", 3, "Batch move / rename", vbOKCancel + vbQuestion) <> vbCancel Then oApp.Quit
  173. End If
  174.  
  175. Function ChkWb
  176.     ChkWb = (TypeName(oWB) <> "Object")
  177. End Function
  178.  
  179. Sub AddFiles(sPath)
  180.     Dim oItem
  181.     If oFSO.FileExists(sPath) Then
  182.         AddFile sPath
  183.         Exit Sub
  184.     End If
  185.     If oFSO.FolderExists(sPath) Then
  186.         For Each oItem In oFSO.GetFolder(sPath).Files
  187.             AddFile oItem.Path
  188.         Next
  189.         For Each oItem In oFSO.GetFolder(sPath).SubFolders
  190.             AddFiles oItem.Path
  191.         Next
  192.        
  193.     End If
  194. End Sub
  195.  
  196. Sub AddFile(sPath)
  197.     Redim Preserve aFiles(UBound(aFiles) + 1)
  198.     aFiles(UBound(aFiles)) = sPath
  199. End Sub
  200.  
  201. Function IsError(sMsg, sRes)
  202.     If Err.Number <> 0 Then
  203.         AddMsg sMsg & vbCrLf & "Error " & Err.Number & ", " & Err.Description, sRes
  204.         IsError = True
  205.         Err.Clear
  206.     Else
  207.         IsError = False
  208.     End If
  209. End Function
  210.  
  211. Sub AddMsg(sMsg, sRes)
  212.     If sRes <> "" Then sRes = sRes & vbCrLf & vbCrLf
  213.     sRes = sRes & sMsg & vbCrLf
  214. End Sub
  215.  
  216. Sub ShowInNotepad(strToFile)
  217.     Dim strTempPath
  218.     With oFSO
  219.         strTempPath = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%TEMP%") & "\" & .GetTempName
  220.         With .CreateTextFile(strTempPath, True, True)
  221.             .WriteLine("Close this window to continue" & vbCrLf & vbCrLf & vbCrLf & strToFile)
  222.             .Close
  223.         End With
  224.         CreateObject("WScript.Shell").Run "notepad.exe " & strTempPath, 1, True
  225.         .DeleteFile (strTempPath)
  226.     End With
  227. End Sub
  228.  
  229. Sub SmartCreateFolder(strFolder)
  230.     ' http://www.visualbasicscript.com/tm.aspx?m=29290
  231.     With oFSO
  232.         If Not .FolderExists(strFolder) then
  233.             SmartCreateFolder(.GetParentFolderName(strFolder))
  234.             .CreateFolder(strFolder)
  235.             If Not oChgFolders.Exists(strFolder) Then
  236.                 oChgFolders.Add strFolder, "" ' add data for created dst folder to be deleted while rollback actions
  237.             End If
  238.         End If
  239.     End With
  240. End Sub
Advertisement
Add Comment
Please, Sign In to add comment