Batch renaming of files using Visual Basic

A rather simple query but I haven't used Visual Basic in 10 years.

I am going to write a small app to loop through scanning a directory containing >1000 PDF files, grab each file name, manipulate the filename, then copy/save with the new filename to a new directory.

What is the correct VB syntax to use to traverse a folder from start to finish, and extraxt the filename component.

I know how to save the files and manipulate the files.
Thanks in advance.
kayseeAsked:
Who is Participating?
 
RobSampsonConnect With a Mentor Commented:
Hi, the FileSystemObject is not capable or creating multiple directories at once. Try using my CreateLocalDirectoryStructure routine to step through creating each folder.

Regards,

Rob.
	dim fso
	dim SourceFile
	dim SourceFolder
	dim FileCounter
 
' Declare variables
	dim strSourceFolder as String
	dim strTargetFolder as String
	dim TempClient as String
	dim TempMatter as String
	dim TempFileName as String
 
' Initialise variables
	strSourceFolder = "\\adelaide\Shared\BusinessIntelligence\SKC_Test_Input"
	strTargetFolder  = "\\adelaide\Shared\BusinessIntelligence\SKC_Test_Output"
	FileCounter= 0
 
' Create/open file object I guess for manipulating file structures and load source directory.
	set fso = CreateObject("Scripting.FileSystemObject")
	set SourceFolder= fso.GetFolder(strSourceFolder )
	
' Loop through source folder 
	for each SourceFile in SourceFolder.Files
		TempClient =  Mid (SourceFile.Name, 1,8 )
		TempMatter =  Mid (SourceFile.Name, 10,8 )
		TempFileName =  Mid (SourceFile.Name, 19,8 )
		
		dim ZerosThere = 1
		While ZerosThere > 0 
			if  Mid (TempClient, 1,1 ) = "0"
				TempClient = Mid(TempClient,2)
			else
				ZerosThere = 0
		Wend
		dim ZerosThere = 1
		While ZerosThere > 0 
			if  Mid TempMatter 1,1 ) = "0"
				TempMatter = Mid(TempMatter ,2)
			else
				ZerosThere = 0
		Wend
		
		strTargetFolder = strTargetFolder & "\" & TempClient & "\" & TempMatter
		
		If objFSO.FolderExists(strTargetFolder) = False Then CreateLocalDirectoryStructure strTargetFolder
 
		fso.CopyFile SourceFile.Path, (strTargetFolder "\" & TempFileName & ".pdf"), True
		FileCounter = FileCounter + 1
	Next
 
 
Sub CreateLocalDirectoryStructure(strPath)
	If Right(strPath, 1) = "\" Then strPath = Left(strPath, Len(strPath) - 1)
	arrBits = Split(strPath, "\")
	strSubPath = arrBits(0)
	If UBound(arrBits) > 0 Then
		For intBit = 1 To UBound(arrBits)
			strSubPath = strSubPath & "\" & arrBits(intBit)
			If objFSO.FolderExists(strSubPath) = False Then objFSO.CreateFolder(strSubPath)
		Next
	End If
End Sub

Open in new window

0
 
appariCommented:
try this

Dim fileName As String

fileName = Dir("C:\test\*.csv")
While fileName <> ""
    Debug.Print fileName
    fileName = Dir()
Wend
0
 
Patrick MatthewsCommented:
Hello kaysee,

1) How are you manipulating the file names?

2) Are you going to execute this using VB, VBA, or VBScript?

Regards,

Patrick
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
RobSampsonCommented:
VBScript code such as this can do the job....

Regards,

Rob.
strSourceFolder = "C:\Temp\PDFs"
strTargetFolder = "C:\Temp\NewPDFs"
If Right(strTargetFolder, 1) = "\" Then strTargetFolder = Left(strTargetFolder, Len(strTargetFolder) - 1)
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strTargetFolder) = False Then objFSO.CreateFolder(strTargetFolder)
For Each objFile In objFSO.GetFolder(strSourceFolder).Files
	If Right(LCase(objFile.Name), 4) = LCase(".pdf") Then
		strNewName = "NewPDF" & objFile.Name
		objFSO.CopyFile objFile.Path, strTargetFolder & "\" & strNewName, True
	End If
Next
MsgBox "Done"

Open in new window

0
 
kayseeAuthor Commented:
Patrick,

1)  Current files use the naming convention of "...\value1_value2_value3.pdf" all in the 1 directory.  I am changing this so that it breaks out the 3 values and rewrites tham into a folder structure based on the values like this: "...\value1\value2\value3.pdf"

2) Originally was going to grab a demo copy of VB to create this one off app but now will just use a VBScript.

Cheers
0
 
RobSampsonCommented:
Hi, given the info you've provided, this will attemp to create the necessary folder structure for the renamed PDF files...

Regards,

Rob.
strSourceFolder = "C:\Temp\"
strTargetFolder = "C:\Temp\NewPDFs"
If Right(strTargetFolder, 1) = "\" Then strTargetFolder = Left(strTargetFolder, Len(strTargetFolder) - 1)
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strTargetFolder) = False Then objFSO.CreateFolder(strTargetFolder)
For Each objFile In objFSO.GetFolder(strSourceFolder).Files
	' Only get PDFs with an underscore in their name
	If Right(LCase(objFile.Name), 4) = LCase(".pdf") And InStr(objFile.Name, "_") > 0 Then
		strNewFullPath = strTargetFolder & "\" & Replace(objFile.Name, "_", "\")
		strNewFileName = Mid(objFile.Name, InStrRev(objFile.Name, "_") + 1)
		'MsgBox "Creating " & Left(strNewFullPath, Len(strNewFullPath) - Len(strNewFileName)) & VbCrLf & " to move in " & VbCrLf & strNewFullPath
		CreateLocalDirectoryStructure Left(strNewFullPath, Len(strNewFullPath) - Len(strNewFullPath))
		objFSO.MoveFile objFile.Path, strNewFullPath
	End If
Next
MsgBox "Done"
 
Sub CreateLocalDirectoryStructure(strPath)
	If Right(strPath, 1) = "\" Then strPath = Left(strPath, Len(strPath) - 1)
	arrBits = Split(strPath, "\")
	strSubPath = arrBits(0)
	If UBound(arrBits) > 0 Then
		For intBit = 1 To UBound(arrBits)
			strSubPath = strSubPath & "\" & arrBits(intBit)
			If objFSO.FolderExists(strSubPath) = False Then objFSO.CreateFolder(strSubPath)
		Next
	End If
End Sub

Open in new window

0
 
kayseeAuthor Commented:
Hi Rob
Utilizing your code I have tried the code below however it is giving me a "Path Not Found" error when I run it, also here are a few other notes about the process that help explain my code:

1) as I said there are 3 "values" and they are always 8 digits long and deliminated by an "_".  Each value uses 0's to fille out their 8 chars.  In my code I want to strip these leading zeros from the 1st 2 Values, for example
convert "...\00012345_00000123_01234567.pdf"  to "...\12345\123\01234567.pdf"

2) My source directory only contains PDF files in that original format.

I get the error "Path Not Found" on the line:

If objFSO.FolderExists(strTargetFolder) = False Then
                  objFSO.CreateFolder(strTargetFolder)

Thanks

	dim fso
	dim SourceFile
	dim SourceFolder
	dim FileCounter
 
' Declare variables
	dim strSourceFolder as String
	dim strTargetFolder as String
	dim TempClient as String
	dim TempMatter as String
	dim TempFileName as String
 
' Initialise variables
	strSourceFolder = "\\adelaide\Shared\BusinessIntelligence\SKC_Test_Input"
	strTargetFolder  = "\\adelaide\Shared\BusinessIntelligence\SKC_Test_Output"
	FileCounter= 0
 
' Create/open file object I guess for manipulating file structures and load source directory.
	set fso = CreateObject("Scripting.FileSystemObject")
	set SourceFolder= fso.GetFolder(strSourceFolder )
	
' Loop through source folder 
	for each SourceFile in SourceFolder.Files
		TempClient =  Mid (SourceFile.Name, 1,8 )
		TempMatter =  Mid (SourceFile.Name, 10,8 )
		TempFileName =  Mid (SourceFile.Name, 19,8 )
		
		dim ZerosThere = 1
		While ZerosThere > 0 
			if  Mid (TempClient, 1,1 ) = "0"
				TempClient = Mid(TempClient,2)
			else
				ZerosThere = 0
		Wend
		dim ZerosThere = 1
		While ZerosThere > 0 
			if  Mid TempMatter 1,1 ) = "0"
				TempMatter = Mid(TempMatter ,2)
			else
				ZerosThere = 0
		Wend
		
		strTargetFolder = strTargetFolder & "\" & TempClient & "\" & TempMatter
		
		If objFSO.FolderExists(strTargetFolder) = False Then 
			objFSO.CreateFolder(strTargetFolder)
 
		fso.CopyFile SourceFile.Path, (strTargetFolder "\" & TempFileName & ".pdf"), True
		FileCounter = FileCounter + 1
	next

Open in new window

0
 
kayseeAuthor Commented:
Sorry for delay in allocating the points.  Understood most of it just didn't know what the "arrbits" parts were doing in "CreateLocalDirectoryStructure"... not too worry it all worked for this one off process, so it was all good.  Thanks for you help.
0
 
RobSampsonCommented:
Thanks for the grade.

The arrBits part basically takes each folder name from a path and creates them in turn.

So if you had
C:\Temp\Temp\Test

arrBits is an array returned by the Split function, splitting by the backslash.

So the arrBits array has four elements now, being
C:
Temp
Temp
Test

then it just rebuilds the path, creating each folder as it goes along....

Regards,

Rob.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.