I have been trying to figure out how to use VBScript to process files in a folder based on their names, create a couple of subfolders, and place the different files into the corresponding subfolders that I have just created.
What I have is as follows.
'Script to move different files into different subfolders based on whether their name contains "Global" or "Profile"
'Script by Simon Barrett
'03/07/2025
'Instructions: Copy this script into whichever folder where you want to organise all the files into their respective folders
Option Explicit ' ALWAYS use Option Explicit!
Dim fso, folder, file
Dim strFolder, newFolderName1, newFolderName2, currentFolder
Dim gFile, pFile
Set fso = CreateObject("Scripting.FileSystemObject")
strFolder = fso.GetParentFolderName(WScript.ScriptFullName)
MsgBox strFolder
folder = strFolder
'Make new folders "Global" and "Profile"
newFolderName1 = fso.BuildPath(currentFolder, "Global")
newFolderName2 = fso.BuildPath(currentFolder, "Profile")
gFile = "*GLOBAL.xlsx"
pFile = "*PROFILE.xlsx"
' Create the folder if it doesn't already exist
If Not fso.FolderExists(newFolderName1) Then
fso.CreateFolder(newFolderName1)
End If
If Not fso.FolderExists(newFolderName2) Then
fso.CreateFolder(newFolderName2)
End If
' Move Global files into the Global Folder
For each file In strFolder.files
'see if the file name contains the word "GLOBAL" and move it to the Global folder
If instr(file.name, gFile) = 1 Then
fso.MoveFile item, newFolderName1 & "\"
End If
Next
For each file In strFolder.files
'see if the file name contains the word "PROFILE" and move it to the Profile folder
If instr(file.name, pFile) = 1 Then
fso.MoveFile item, newFolderName2 & "\"
End If
Next
' Notify the user
MsgBox "Folders Created and files moved!"
I'm getting an error on the first for loop, and I'm not sure exactly why.
I've tried using for each file in folder.files as well, but to no avail.
The error I receive is Object Required.
I suspect it's something to do with a string vs an object, but I don't know how to fix it.
I need to retrieve the current folder or directory and use it in my for loop, where I'm looking, and it's this part I'm having trouble with.
I have tried looking at suggested questions to see if they answer my question, but I still cannot work it out.