Please can I have a VBA code that will do the following:
Search all Folders in the current workbook path
and look for any file that ends with the word 'Quote' before the dot that precedes the file name extension
as in this example 'This is an example Quote.pdf'
For each file that is found, write the result to a text document as such;
Name of Folder whaere the file was found,
line break
Name of the file found.
Do this for all folders that the folder name does not start with the letter 'z'
Assistant
Here is a VBA code that achieves the described task:
Sub SearchFiles()
Dim FolderPath As String
Dim FileName As String
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim outPutFile As Object
Dim outPutFilePath As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set outPutFile = objFSO.CreateTextFile(ThisWorkbook.Path & "\Output.txt")
For Each objFolder In objFSO.GetFolder(ThisWorkbook.Path).SubFolders
If Left(objFolder.Name, 1) <> "z" Then
For Each objFile In objFolder.Files
If InStrRev(objFile.Name, ".") > 0 Then
FileName = Left(objFile.Name, InStrRev(objFile.Name, ".") - 1)
If Right(FileName, 5) = "Quote" Then
outPutFile.WriteLine objFolder.Name
outPutFile.WriteLine objFile.Name
outPutFile.WriteLine ""
End If
End If
Next objFile
End If
Next objFolder
outPutFile.Close
Set objFSO = Nothing
Set outPutFile = Nothing
MsgBox "Search completed. Results written to Output.txt file"
End Sub
User
Thanks I got it to work
Assistant
You're welcome! If you have any more questions or need further assistance with VBA or any other topic, feel free to ask. I'm here to help!
User
In the code below, can you write it so that the QuoteFiles.txt stays open and active: Option Explicit
Sub SearchFilesQuote()
Dim FolderPath As String
Dim folderName As String
Dim FileName As String
Dim outPutFile As String
Dim outputStream As Object
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim outPutFilePath As String
Dim totalFolders As Integer
Dim foldersWithQuotes As Integer
totalFolders = 0
foldersWithQuotes = 0
' Get current workbook path
FolderPath = ThisWorkbook.path
' Define output file path
outPutFile = FolderPath & "\QuoteFiles.txt"
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open the output file in append mode (True)
Set outputStream = objFSO.CreateTextFile(outPutFile, True)
For Each objFolder In objFSO.GetFolder(FolderPath).SubFolders
If Left(objFolder.Name, 1) <> "z" Then
For Each objFile In objFolder.files
If InStrRev(objFile.Name, ".") > 0 Then
FileName = Left(objFile.Name, InStrRev(objFile.Name, ".") - 1)
If Right(FileName, 5) = "Quote" Then
outputStream.WriteLine objFolder.Name
outputStream.WriteLine objFile.Name
outputStream.WriteLine """"
End If
End If
Next objFile
End If
Next objFolder
outputStream.Close
Set objFSO = Nothing
Set outputStream = Nothing
MsgBox "Search completed. Results written to QuoteFiles.txt file"""
Assistant
To keep the QuoteFiles.txt file open and active after writing the results, you can modify the code to open the file in append mode with ShareMode set to 8 (for Read/Write). Here's the modified code:
Option Explicit
Sub SearchFilesQuote()
Dim FolderPath As String
Dim folderName As String
Dim FileName As String
Dim outPutFilePath As String
Dim outputStream As Object
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim totalFolders As Integer
Dim foldersWithQuotes As Integer
totalFolders = 0
foldersWithQuotes = 0
' Get current workbook path
FolderPath = ThisWorkbook.Path
' Define output file path
outPutFilePath = FolderPath & "\QuoteFiles.txt"
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open the output file in append mode (True) with ShareMode 8 (ReadWrite)
Set outputStream = objFSO.OpenTextFile(outPutFilePath, 8, True)
For Each objFolder In objFSO.GetFolder(FolderPath).SubFolders
If Left(objFolder.Name, 1) <> "z" Then
For Each objFile In objFolder.Files
If InStrRev(objFile.Name, ".") > 0 Then
FileName = Left(objFile.Name, InStrRev(objFile.Name, ".") - 1)
If Right(FileName, 5) = "Quote" Then
outputStream.WriteLine objFolder.Name
outputStream.WriteLine objFile.Name
outputStream.WriteLine ""
End If
End If
Next objFile
End If
Next objFolder
MsgBox "Search completed. Results written to QuoteFiles.txt file"
'Set objFSO = Nothing 'No need to set to Nothing
'Set outputStream = Nothing 'No need to set to Nothing
End Sub
User
Error: Invalid procedure call or argument on the line 'Set outputStream = objFSO.OpenTextFile(outPutFilePath, 8, True)
Assistant
Apologies for the error. Let's modify the code to address the "Invalid procedure call or argument" issue by opening the output file in append mode without specifying the ShareMode parameter. Here is the updated code:
Option Explicit
Sub SearchFilesQuote()
Dim FolderPath As String
Dim folderName As String
Dim FileName As String
Dim outPutFilePath As String
Dim outputStream As Object
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
' Get current workbook path
FolderPath = ThisWorkbook.Path
' Define output file path
outPutFilePath = FolderPath & "\QuoteFiles.txt"
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open the output file in append mode (True)
Set outputStream = objFSO.OpenTextFile(outPutFilePath, 8, True) ' Use 8 for append mode
For Each objFolder In objFSO.GetFolder(FolderPath).SubFolders
If Left(objFolder.Name, 1) <> "z" Then
For Each objFile In objFolder.Files
If InStrRev(objFile.Name, ".") > 0 Then
FileName = Left(objFile.Name, InStrRev(objFile.Name, ".") - 1)
If Right(FileName, 5) = "Quote" Then
outputStream.WriteLine objFolder.Name
outputStream.WriteLine objFile.Name
outputStream.WriteLine ""
End If
End If
Next objFile
End If
Next objFolder
MsgBox "Search completed. Results written to QuoteFiles.txt file"
' Do not close the outputStream here to keep the file open
Set objFSO = Nothing
End Sub
User
Error: Invalid procedure call or argument, on the line 'Set outputStream = objFSO.OpenTextFile(outPutFilePath, 8, True)
Assistant
Apologies for the confusion earlier. Let's adjust the code to keep the QuoteFiles.txt file open by opening it in append mode without specifying the ShareMode parameter. Here is the updated code:
Option Explicit
Sub SearchFilesQuote()
Dim FolderPath As String
Dim folderName As String
Dim FileName As String
Dim outPutFilePath As String
Dim outputStream As Object
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
' Get current workbook path
FolderPath = ThisWorkbook.Path
' Define output file path
outPutFilePath = FolderPath & "\QuoteFiles.txt"
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the output file exists, if not create it
If Not objFSO.FileExists(outPutFilePath) Then
objFSO.CreateTextFile(outPutFilePath).Close
End If
' Open the output file in append mode
Set outputStream = objFSO.OpenTextFile(outPutFilePath, 8) ' Use 8 for append mode
For Each objFolder In objFSO.GetFolder(FolderPath).SubFolders
If Left(objFolder.Name, 1) <> "z" Then
For Each objFile In objFolder.Files
If InStrRev(objFile.Name, ".") > 0 Then
FileName = Left(objFile.Name, InStrRev(objFile.Name, ".") - 1)
If Right(FileName, 5) = "Quote" Then
outputStream.WriteLine objFolder.Name
outputStream.WriteLine objFile.Name
outputStream.WriteLine ""
End If
End If
Next objFile
End If
Next objFolder
MsgBox "Search completed. Results written to QuoteFiles.txt file"
' Do not close the outputStream here to keep the file open
Set objFSO = Nothing
End Sub
User
I am getting the smae error but now on this line: objFSO.CreateTextFile(outPutFilePath).Close
Assistant
I see, let's adjust the code slightly to handle the "Invalid procedure call or argument" error when creating the text file. We will use error handling to ensure that the file is closed properly in case it was already open. Here's the updated code:
Option Explicit
Sub SearchFilesQuote()
Dim FolderPath As String
Dim folderName As String
Dim FileName As String
Dim outPutFilePath As String
Dim outputStream As Object
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
' Get current workbook path
FolderPath = ThisWorkbook.Path
' Define output file path
outPutFilePath = FolderPath & "\QuoteFiles.txt"
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open the output file in append mode
On Error Resume Next
Set outputStream = objFSO.OpenTextFile(outPutFilePath, 8) ' Use 8 for append mode
On Error GoTo 0
' If outputStream is not set (file doesn't exist or couldn't be opened), create a new file
If outputStream Is Nothing Then
Set outputStream = objFSO.CreateTextFile(outPutFilePath)
End If
For Each objFolder In objFSO.GetFolder(FolderPath).SubFolders
If Left(objFolder.Name, 1) <> "z" Then
For Each objFile In objFolder.Files
If InStrRev(objFile.Name, ".") > 0 Then
FileName = Left(objFile.Name, InStrRev(objFile.Name, ".") - 1)
If Right(FileName, 5) = "Quote" Then
outputStream.WriteLine objFolder.Name
outputStream.WriteLine objFile.Name
outputStream.WriteLine ""
End If
End If
Next objFile
End If
Next objFolder
MsgBox "Search completed. Results written to QuoteFiles.txt file"
' Do not close the outputStream here to keep the file open
Set objFSO = Nothing
End Sub
User
Same error but now on: Set outputStream = objFSO.OpenTextFile(outPutFilePath, 8)
Assistant
It seems there might be some issue with the file path or access permissions. Let's try a different approach by first checking if the file exists before attempting to open it. If the file exists, we will try to open it in append mode; otherwise, we will create a new file. Here is the updated code:
User
All the methods you have provided in keeping the text file open has failed. Can you write a simple VBA code to open the text file QuoteFiles.txt. It is in the same path as the current workbook
Assistant
Certainly! Below is a simple VBA code that opens the QuoteFiles.txt in the same path as the current workbook:
Sub OpenQuoteFile()
Dim filePath As String
Dim shellApp As Object
' Get the path of the QuoteFiles.txt in the same directory as the workbook
filePath = ThisWorkbook.Path & "\QuoteFiles.txt"
' Create a Shell object
Set shellApp = CreateObject("Shell.Application")
' Check if the file exists before trying to open it
If Dir(filePath) <> "" Then
' Open the text file using the default text editor
shellApp.Open filePath
Else
MsgBox "QuoteFiles.txt does not exist in the directory of the current workbook."
End If
' Release the Shell object
Set shellApp = Nothing
End Sub
You can run this code in the VBA editor (Alt + F11) to open the QuoteFiles.txt file using the default text editor. Make sure the QuoteFiles.txt is in the same directory as the workbook where you are running this code. If the file exists, it will be opened; otherwise, a message will be displayed. Let me know if you need any further assistance.
User
No errors, no message, but the txt file does not open
Assistant
If the text file "QuoteFiles.txt" is not opening when running the code, it might be due to the default program associated with opening .txt files on your system. Let's try a different approach using the Shell function in VBA to open the text file with the default program. Here's the updated code:
Sub OpenQuoteFile()
Dim filePath As String
' Get the path of the QuoteFiles.txt in the same directory as the workbook
filePath = ThisWorkbook.Path & "\QuoteFiles.txt"
' Check if the file exists
If Dir(filePath) <> "" Then
' Open the text file with the default program
Shell "cmd /c start " & filePath, vbNormalFocus
Else
MsgBox "QuoteFiles.txt does not exist in the directory of the current workbook."
End If
End Sub
This code uses the Shell function to open the text file with the default program associated with .txt files on your system. Run this updated code in the VBA editor, and if the file exists, it should open with the default text editor. Let me know if you encounter any issues.
User
The Vba code bellow works perfectly.
Can you please adjust it to do the following:
Instead of writing the results to a text.file,
write the reults to an excel sheet named 'PENDING QUOTES'
Each result written to a seperate row, with the file name in column A, the Folder name in column B
starting from row 2.
Sub SearchFiles()
Dim FolderPath As String
Dim folderName As String
Dim FileName As String
Dim outPutFile As String
Dim outputStream As Object
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim outPutFilePath As String
Dim totalFolders As Integer
Dim foldersWithQuotes As Integer
totalFolders = 0
foldersWithQuotes = 0
' Get current workbook path
FolderPath = ThisWorkbook.path
' Define output file path
outPutFile = FolderPath & "\QuoteFiles.txt"
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open the output file in append mode (True)
Set outputStream = objFSO.CreateTextFile(outPutFile, True)
For Each objFolder In objFSO.GetFolder(FolderPath).SubFolders
If Left(objFolder.Name, 1) <> "z" Then
For Each objFile In objFolder.files
If InStrRev(objFile.Name, ".") > 0 Then
FileName = Left(objFile.Name, InStrRev(objFile.Name, ".") - 1)
If Right(FileName, 5) = "Quote" Then
outputStream.WriteLine "PENDING QUOTE FOUND IN . . ."
outputStream.WriteLine objFolder.Name
outputStream.WriteLine objFile.Name
outputStream.WriteLine "" & vbCrLf
End If
End If
Next objFile
End If
Next objFolder
outputStream.Close
Set objFSO = Nothing
Set outputStream = Nothing
Call OpenQuoteFile
Assistant
To modify the existing code to write the results to an Excel sheet named "PENDING QUOTES" with each result in a separate row (file name in column A and folder name in column B starting from row 2), we need to make changes to record the data properly in the Excel sheet. Here is the updated code:
User
Can you please write me a VBA code that will do the following:
In sheet 'PENDING QUOTES'
When I double click on a cell that is not empty in column A
Find the Folder in the workbook path that has the same name as the value in column B
and in the folder found,
Find the File that has the same name as the value in column A
and change the name of the file found as described.
Delete the word Quote at the end of the filename just before the file extension
and any empty space before the word Quote if there is.
As in the examples shown bellow where spaces and no spaces exist:
'This file Quote.pdf' to be changed to 'This file.pdf'
'This file 2024Quote.pdf' to be changed to 'This file 2024.pdf'
Assistant
User
Error: File already exists, on the line 'objFile.Name = Left(objFile.Name, Len(FileName)) & "." & Extension'
Assistant
User
Same error: File Name already Exists, on the line 'objFile.Name = NewFileName'
Assistant
User
Before using your new suggestion, please see the changes I have made to the code to indicate the correct path to the folder. Also, when I checked the folder, the NewFileName has not been created therefore it should not already exist. Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
Assistant
Your changes look good. Since you are checking if the NewFileName already exists before renaming the file, it should not encounter the "File already exists" error.
You have correctly pointed out the changes in the path to the folder and removing the Trim function on the FolderName. Also, your code indicates that NewFileName should not already exist before renaming the file, which aligns with our method of checking for the file's existence before renaming.
Please go ahead and try running your updated code in the VBA editor by double-clicking on a non-empty cell in column A of the "PENDING QUOTES" sheet to see if the file renaming works as expected. If you encounter any issues or require further assistance, feel free to let me know.
User
It appears that the problem starts on this line 'NewFileName = Left(objFile.Name, Len(FileName)) & "." & Extension', because the NewFileName is exactly the same as the FileName. The NewFileName should have the word Quote at the end of the file name deleted
Assistant
User
this line of quote still does not remove the word Quote: NewFileName = Replace(FileName, " Quote.", ".") & "." & Extension
Assistant
User
The FileName is 'Test file Quote.pdf' How will you write this line of code to change the FileNmae to 'Test File.pdf' : NewFileName = Replace(FileName, "Quote.", ".")
Assistant
To remove the word "Quote" at the end of the FileName, including the space before it, you can use the VBA Replace function to search for the specific string " Quote" and replace it with an empty string. Here is how you can adjust the code line to change the FileName from 'Test file Quote.pdf' to 'Test File.pdf':
In this adjustment, the Replace function will search for the string " Quote" (including the leading space) in the FileName and replace it with an empty string, effectively removing the word "Quote" with the space before it. The rest of the renaming process remains the same. Please try this adjustment and check if it correctly renames the file as intended.
User
My Double Click event is not being activated by a double click: Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.path
'FolderName = Trim(Target.Offset(0, 1).Value)
FolderName = Target.Offset(0, 1).Value
FileName = Target.Value
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
'If objFSO.FolderExists(FolderPath & "" & FolderName) Then
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.files
If Left(objFile.Name, Len(FileName)) = FileName Then
' Prepare the new file name
'NewFileName = Replace(FileName, " Quote.", ".") & "." & Extension
NewFileName = Replace(FileName, "Quote", "") & "." & Extension
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.path & "" & NewFileName) Then
' Modify the file name if found
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
Else
MsgBox "Folder '" & FolderName & " ' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
End If
Cancel = True
Assistant
User
The VBA code below now works. How do I stop it from going into edit mode in the cell I double clicked on: Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.path
FolderName = Target.Offset(0, 1).Value
FileName = Target.Value
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
'If objFSO.FolderExists(FolderPath & "" & FolderName) Then
If objFSO.FolderExists(FolderPath & "" & FolderName) Then
'Set objFolder = objFSO.GetFolder(FolderPath & "" & FolderName)
Set objFolder = objFSO.GetFolder(FolderPath & "" & FolderName)
Assistant
User
The code works perfectly except for one issue. If there is a space before the leter Q in the word Quote, it doe not delete the space. In some of the file names there is a space before the letter Q and in other file names, there is no space. Can VBA identify if there is a space and also delete the space from the NewFIleName, and if there is no space only delete the word 'Quote'
Assistant
User
where " Quote" was found, it deleted the space before Quote. Where "Quote" was found, it deleted Quote, but it added the file extension twice. for examle 'This exampleQuote.pdf' was changed to 'This example.pdf.pdf' : QuotePosition = InStrRev(objFile.Name, " Quote")
If QuotePosition > 0 Then
' Prepare the new file name by removing ' Quote'
NewFileName = Left(objFile.Name, QuotePosition - 1) & "." & Extension
ElseIf InStrRev(objFile.Name, "Quote") > 0 Then
' Prepare the new file name by removing 'Quote'
NewFileName = Replace(objFile.Name, "Quote", "") & "." & Extension
Else
NewFileName = objFile.Name ' No change
End If
Assistant
You can run this code in the VBA editor (Alt + F11) in your Excel workbook. It will search all folders in the current workbook path for files ending with 'Quote' before the dot and write the results to a text document named Output.txt.
End Sub
This code will keep the QuoteFiles.txt file open and active after writing the results. Make sure to manually close the file when you are done with it. Let me know if you have any questions or need further assistance.
This updated code should resolve the issue and keep the QuoteFiles.txt file open for further use. Let me know if you encounter any more difficulties or require additional assistance.
This updated code should resolve the issue, and the QuoteFiles.txt file should remain open after writing the results. Let me know if you encounter any more issues or need further assistance.
This updated code should handle the error when creating or opening the output file. It will create a new file if the specified file does not exist or could not be opened. Let me know if you encounter any more issues.
Option Explicit
Sub SearchFilesQuote()
Dim FolderPath As String
Dim folderName As String
Dim FileName As String
Dim outPutFilePath As String
Dim outputStream As Object
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
' Get current workbook path
FolderPath = ThisWorkbook.Path
' Define output file path
outPutFilePath = FolderPath & "\QuoteFiles.txt"
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the file exists
If objFSO.FileExists(outPutFilePath) Then
' Open the output file in append mode
On Error Resume Next
Set outputStream = objFSO.OpenTextFile(outPutFilePath, 8) ' Use 8 for append mode
On Error GoTo 0
End If
' If outputStream is not set (file doesn't exist or couldn't be opened), create a new file
If outputStream Is Nothing Then
Set outputStream = objFSO.CreateTextFile(outPutFilePath)
End If
For Each objFolder In objFSO.GetFolder(FolderPath).SubFolders
If Left(objFolder.Name, 1) <> "z" Then
For Each objFile In objFolder.Files
If InStrRev(objFile.Name, ".") > 0 Then
FileName = Left(objFile.Name, InStrRev(objFile.Name, ".") - 1)
If Right(FileName, 5) = "Quote" Then
outputStream.WriteLine objFolder.Name
outputStream.WriteLine objFile.Name
outputStream.WriteLine ""
End If
End If
Next objFile
End If
Next objFolder
MsgBox "Search completed. Results written to QuoteFiles.txt file"
' Do not close the outputStream here to keep the file open
Set objFSO = Nothing
End Sub
This code checks if the output file exists before trying to open it in append mode. If the file does not exist or could not be opened, it creates a new file. Let me know if this resolves the issue or if you encounter any more difficulties.
End Sub
Sub SearchFiles()
Dim FolderPath As String
Dim FileName As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim wsOutput As Worksheet
Dim rowNum As Long
' Get current workbook path
FolderPath = ThisWorkbook.Path
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Set the worksheet for output or create new if not existing
On Error Resume Next
Set wsOutput = ThisWorkbook.Sheets("PENDING QUOTES")
On Error GoTo 0
If wsOutput Is Nothing Then
Set wsOutput = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
wsOutput.Name = "PENDING QUOTES"
Else
wsOutput.Cells.Clear
End If
' Set the initial row number
rowNum = 2
For Each objFolder In objFSO.GetFolder(FolderPath).SubFolders
If Left(objFolder.Name, 1) <> "z" Then
For Each objFile In objFolder.Files
If InStrRev(objFile.Name, ".") > 0 Then
FileName = Left(objFile.Name, InStrRev(objFile.Name, ".") - 1)
If Right(FileName, 5) = "Quote" Then
wsOutput.Cells(rowNum, 1).Value = objFile.Name
wsOutput.Cells(rowNum, 2).Value = objFolder.Name
rowNum = rowNum + 1
End If
End If
Next objFile
End If
Next objFolder
MsgBox "Search completed. Results written to PENDING QUOTES worksheet."
End Sub
This code will search for files with "Quote" in their name and write the results (file name in column A and folder name in column B) to the "PENDING QUOTES" worksheet in the same workbook. If the worksheet doesn't exist, it will be created, and if it exists, the previous data will be cleared. Run this modified code in the VBA editor to achieve the desired functionality.
To achieve the described functionality of double-clicking on a cell in column A of the "PENDING QUOTES" sheet, finding the corresponding folder with the same name as the value in column B, locating and modifying the file name to remove the word "Quote" just before the file extension, you can use the following VBA code:
Copy and paste the code below into the code module for the "PENDING QUOTES" worksheet in the VBA editor (Alt + F11), and it will run whenever you double-click on a non-empty cell in column A.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.Path
FolderName = Trim(Target.Offset(0, 1).Value)
FileName = Trim(Target.Value)
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.Files
If Left(objFile.Name, Len(FileName)) = FileName Then
' Modify the file name if found
objFile.Name = Left(objFile.Name, Len(FileName)) & "." & Extension
Exit For ' Exit the loop after renaming the file
End If
Next objFile
Else
MsgBox "Folder '" & FolderName & "' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
End If
End Sub
When you double-click on a non-empty cell in column A of the "PENDING QUOTES" sheet, this code will search for a folder with the same name as the value in column B in the workbook path. If the folder is found, it will look for a file with a name matching column A (excluding "Quote" before the extension) and rename that file in the folder. Any extraneous spaces before or after the word "Quote" will also be removed from the file name during the renaming process.
To avoid the "File already exists" error when trying to rename a file that already exists with the same name, we can first check if the new file name to be assigned exists before renaming it. Here's the modified code to handle this scenario:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.Path
FolderName = Trim(Target.Offset(0, 1).Value)
FileName = Trim(Target.Value)
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.Files
If Left(objFile.Name, Len(FileName)) = FileName Then
' Prepare the new file name
NewFileName = Left(objFile.Name, Len(FileName)) & "." & Extension
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.Path & "\" & NewFileName) Then
' Rename the file
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
Else
MsgBox "Folder '" & FolderName & "' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
End If
End Sub
This modified code includes a check to see if the new file name already exists in the folder before attempting to rename the file. If the new file name is already in use, it will not attempt to rename the file, thus avoiding the "File already exists" error. Run this updated code in the VBA editor to handle the renaming process efficiently. Let me know if you encounter any more issues.
If you are still encountering the "File already exists" error even after checking if the new file name already exists before renaming, we can include a rename strategy to handle this situation. One common approach is to append a number to the new file name if a file with the same name already exists. Here's the updated code with this strategy:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
Dim Counter As Integer
' Initialize counter for adding a number to the file name if needed
Counter = 1
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.Path
FolderName = Trim(Target.Offset(0, 1).Value)
FileName = Trim(Target.Value)
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.Files
If Left(objFile.Name, Len(FileName)) = FileName Then
Do
' Prepare the new file name with counter if needed
NewFileName = Left(FileName, Len(FileName)) & IIf(Counter > 1, " " & Counter, "") & "." & Extension
Counter = Counter + 1
Loop While objFSO.FileExists(objFolder.Path & "\" & NewFileName)
' Rename the file
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
Next objFile
Else
MsgBox "Folder '" & FolderName & "' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
End If
End Sub
This updated code includes a loop to increment a counter and add it to the file name if the new file name already exists in the folder. Run this modified code in the VBA editor to handle file renaming with the counter strategy to avoid conflicts due to existing file names. Let me know if you need further assistance.
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.path
'FolderName = Trim(Target.Offset(0, 1).Value)
FolderName = Target.Offset(0, 1).Value
FileName = Target.Value
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
'If objFSO.FolderExists(FolderPath & "" & FolderName) Then
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.files
If Left(objFile.Name, Len(FileName)) = FileName Then
' Prepare the new file name
NewFileName = Left(objFile.Name, Len(FileName)) & "." & Extension
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.path & "" & NewFileName) Then
' Modify the file name if found
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
Else
MsgBox "Folder '" & FolderName & " ' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
End If
End Sub
To resolve the issue where the NewFileName is the same as the FileName before renaming, we need to modify the NewFileName to delete the word "Quote" at the end of the file name before constructing the new file name. Here's an updated version of the code to address this:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.Path
'FolderName = Trim(Target.Offset(0, 1).Value)
FolderName = Target.Offset(0, 1).Value
FileName = Target.Value
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.Files
If Left(objFile.Name, Len(FileName)) = FileName Then
' Prepare the new file name removing 'Quote' at the end
NewFileName = Replace(FileName, " Quote.", ".") & "." & Extension
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.Path & "\" & NewFileName) Then
' Rename the file
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
Else
MsgBox "Folder '" & FolderName & "' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
End If
End Sub
In this updated code, the NewFileName is created by replacing the "Quote" at the end of the FileName before constructing the new file name for renaming. This should address the issue where NewFileName was the same as FileName before renaming. Please try running this modified code and double-clicking on a non-empty cell in column A to see if the renaming process works correctly now.
I apologize for the oversight. Let's adjust the line where the word "Quote" is removed from the file name before creating the new file name. We will use a different approach to remove the word "Quote" from the file name. Here is the updated code:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.Path
'FolderName = Trim(Target.Offset(0, 1).Value)
FolderName = Target.Offset(0, 1).Value
FileName = Target.Value
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - Len(" Quote"))
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.Files
If Left(objFile.Name, Len(FileName)) = FileName Then
' Prepare the new file name
NewFileName = FileName & "." & Extension
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.Path & "\" & NewFileName) Then
' Rename the file
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
Else
MsgBox "Folder '" & FolderName & "' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
End If
End Sub
In this updated code, the FileName is modified to remove the word "Quote" at the end of the file name, ensuring that the NewFileName does not include "Quote" before the file extension. Please try running this modified code and double-clicking on a non-empty cell in column A to see if the renaming process now works as intended. If you have any more issues or need further assistance, feel free to ask.
End Sub
If the Worksheet_BeforeDoubleClick event is not being triggered by double-clicking on a cell, we can try a different event approach to handle the double-click action that triggers the file renaming procedure. We can switch to the Worksheet_SelectionChange event, which captures the selected cell and checks for a double-click condition.
Here is an updated version of your code implementing the Worksheet_SelectionChange event for detecting a double-click:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Static sDblClickTime As Date
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
Dim dblClickDelay As Date
dblClickDelay = Now - TimeSerial(0, 0, 0)
If Target.Column = 1 And Target.Value <> "" Then
' Check for double-click by comparing the time difference
If dblClickDelay < sDblClickTime + TimeSerial(0, 0, 1) Then ' Adjust time interval as needed
' Reset the double-click time
sDblClickTime = Now
' Get current workbook path
FolderPath = ThisWorkbook.Path
FolderName = Target.Offset(0, 1).Value
FileName = Target.Value
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create a Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.Files
If Left(objFile.Name, Len(FileName)) = FileName Then
' Prepare the new file name
NewFileName = Replace(FileName, "Quote", "") & "." & Extension
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.Path & "\" & NewFileName) Then
' Modify the file name if found
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
Else
MsgBox "Folder '" & FolderName & "' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
End If
End If
End Sub
Please add this revised code to the worksheet module and test by double-clicking on a non-empty cell in column A of the "PENDING QUOTES" sheet to initiate the file renaming process. This modification utilizes the Worksheet_SelectionChange event to detect a double-click action and trigger the file renaming logic accordingly. Adjust the time interval in the comparison if needed based on the delay between double-clicks. Let me know if you encounter any difficulties or require further assistance.
' Loop through the files in the folder
For Each objFile In objFolder.files
If Left(objFile.Name, Len(FileName)) = FileName Then
' Prepare the new file name
NewFileName = Replace(FileName, "Quote", "") & "." & Extension
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.path & "" & NewFileName) Then
' Modify the file name if found
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
MsgBox "File name changed to - " & NewFileName
Else
MsgBox "Folder '" & FolderName & " ' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
End If
End Sub
To prevent Excel from entering edit mode in the cell after a double-click event, you can set the Cancel parameter to True. This will cancel the default action associated with the double-click, which is to start editing the cell content. Here's how you can update your existing code to achieve this:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.Path
FolderName = Target.Offset(0, 1).Value
FileName = Target.Value
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.Files
If Left(objFile.Name, Len(FileName)) = FileName Then
' Prepare the new file name
NewFileName = Replace(FileName, "Quote", "") & "." & Extension
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.Path & "\" & NewFileName) Then
' Modify the file name if found
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
MsgBox "File name changed to - " & NewFileName
Else
MsgBox "Folder '" & FolderName & "' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
' Cancel the default double-click action to prevent entering edit mode
Cancel = True
End If
End Sub
By setting Cancel = True at the end of the event code, any subsequent steps for editing the cell content will be canceled after the double-click event. This will prevent Excel from entering edit mode in the cell and the MsgBox will show the message "File name changed to - NewFileName". Feel free to try running this updated code and let me know if you encounter any issues.
To handle cases where the word "Quote" may have a space before it in some file names, you can modify the code to check for the presence of a space before "Quote" and handle the deletion accordingly. Here's the updated code:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
Dim QuotePosition As Long
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.Path
FolderName = Target.Offset(0, 1).Value
FileName = Target.Value
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - 1)
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.Files
If Left(objFile.Name, Len(FileName)) = FileName Then
QuotePosition = InStrRev(objFile.Name, " Quote")
If QuotePosition > 0 Then
' Prepare the new file name by removing ' Quote'
NewFileName = Left(objFile.Name, QuotePosition - 1) & "." & Extension
ElseIf InStrRev(objFile.Name, "Quote") > 0 Then
' Prepare the new file name by removing 'Quote'
NewFileName = Replace(objFile.Name, "Quote", "") & "." & Extension
Else
NewFileName = objFile.Name ' No change
End If
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.Path & "\" & NewFileName) Then
' Modify the file name if found
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
MsgBox "File name changed to - " & NewFileName
Else
MsgBox "Folder '" & FolderName & "' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
' Cancel the default double-click action to prevent entering edit mode
Cancel = True
End If
End Sub
In this updated code, the position of the word "Quote" is checked to see if there is a space before it. If a space is found before "Quote", it will be removed along with the space. If there is no space before "Quote", only the word "Quote" will be removed. This approach should correctly handle both cases where "Quote" has a space before it and where it doesn't. Feel free to test this updated code and let me know if you encounter any issues.
To address the issue where the file extension is duplicated when removing the word "Quote" and space " Quote" from the file name, we can modify the code to ensure that the file extension is appended only once after the renaming process. We will adjust the NewFileName construction to include the extension at the appropriate position. Here's the updated code:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FolderPath As String
Dim FolderName As String
Dim FileName As String
Dim Extension As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim NewFileName As String
Dim QuotePosition As Long
' Check if the double-clicked cell is in column A and not empty
If Target.Column = 1 And Target.Value <> "" Then
' Get current workbook path
FolderPath = ThisWorkbook.Path
FolderName = Target.Offset(0, 1).Value
FileName = Target.Value
Extension = Right(FileName, Len(FileName) - InStrRev(FileName, "."))
FileName = Left(FileName, InStrRev(FileName, ".") - Len(" Quote"))
' Create Scripting.FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the folder with the same name exists
If objFSO.FolderExists(FolderPath & "\" & FolderName) Then
Set objFolder = objFSO.GetFolder(FolderPath & "\" & FolderName)
' Loop through the files in the folder
For Each objFile In objFolder.Files
If Left(objFile.Name, Len(FileName)) = FileName Then
QuotePosition = InStrRev(objFile.Name, " Quote")
If QuotePosition > 0 Then
' Prepare the new file name by removing ' Quote'
NewFileName = Left(objFile.Name, QuotePosition - 1) & "." & Extension
ElseIf InStrRev(objFile.Name, "Quote") > 0 Then
' Prepare the new file name by removing 'Quote'
NewFileName = Replace(objFile.Name, "Quote", "", , , vbTextCompare) & "." & Extension
Else
NewFileName = objFile.Name ' No change
End If
' Check if the new file name already exists in the folder
If Not objFSO.FileExists(objFolder.Path & "\" & NewFileName) Then
' Modify the file name if found
objFile.Name = NewFileName
Exit For ' Exit the loop after renaming the file
End If
End If
Next objFile
MsgBox "File name changed to - " & NewFileName
Else
MsgBox "Folder '" & FolderName & "' not found in the workbook path."
End If
Set objFSO = Nothing ' Release the FileSystemObject
' Cancel the default double-click action to prevent entering edit mode
Cancel = True
End If
End Sub
In this updated code, the NewFileName construction has been adjusted to include the file extension only once at the end of the renamed file name. The Replace function for removing "Quote" is set to be case-insensitive (using the vbTextCompare argument) to ensure that "Quote" can be removed regardless of its case in the file name. Feel free to try this revised code and let me know if it correctly renames the files without duplicating the file extension.