Search code examples
vbscriptdirectoryfilenames

Look for a word within the folder name with VB scripting


How can i read a folder name with vb script and look for a particular word?

EG:

Folder name = 1234abc_Complete How can i get the text complete and store as a variable?

Thank you!


Solution

  • The following code should do as you require.

    Option Explicit
    ' create a FileSystemObject
    Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
    ' Set a reference to the folder which contains the folders you want to look through
    Dim oFolder : Set oFolder = oFso.GetFolder("PathToFolderInHere")
    Dim oSubFolder, myVar
    ' loop through each subfolder
    For Each oSubFolder in oFolder.SubFolders
        ' If the oSubFolder contains the word complete then set myVar and exit the loop
        If InStr(1, oSubFolder.Name, "complete", vbTextCompare) > 0 Then
            myVar = oSubFolder.Name
            Exit For
        End If
    Next
    
    ' do whatever with myVar (the folder name you wanted in the variable).