Solved

Batch renaming of files using Visual Basic

Posted on 2008-06-16
9
496 Views
Last Modified: 2013-11-25
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.
0
Comment
Question by:kaysee
9 Comments
 
LVL 39

Expert Comment

by:appari
ID: 21798672
try this

Dim fileName As String

fileName = Dir("C:\test\*.csv")
While fileName <> ""
    Debug.Print fileName
    fileName = Dir()
Wend
0
 
LVL 92

Expert Comment

by:Patrick Matthews
ID: 21798765
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
 
LVL 65

Expert Comment

by:RobSampson
ID: 21807477
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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:kaysee
ID: 21819274
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
 
LVL 65

Expert Comment

by:RobSampson
ID: 21819581
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
 

Author Comment

by:kaysee
ID: 21819844
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
 
LVL 65

Accepted Solution

by:
RobSampson earned 125 total points
ID: 21819873
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
 

Author Closing Comment

by:kaysee
ID: 31470435
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
 
LVL 65

Expert Comment

by:RobSampson
ID: 21862218
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question