Excel VBA let user to input new sheet name - excel

I have code to list all files in chosen folder. Now it creates new sheet with name "Files". How to modify this code to let user input folder name every time he clicks the button? So basically scenario would look like this:
Click button
Choose folder to List files from
Type new Worksheet name where files will be listed
Code processed
Click button
Choose folder to List files from
Type new Worksheet name where files will be listed
Code processed
Same actions till the end of the world
I have tried this one but probably have mistakes inputting to my code:
Dim NewName As String
NewName = InputBox("What Do you Want to Name the Sheet1 ?")
Sheets("Sheet1").Name = NewName
I have tried to modify this with:
Sheets.Add.Name = NewName
Sheets(NewName).[A1].Resize(AllFiles.Count, 1) = WorksheetFunction.Transpose(AllFiles.keys)
My code for listing files and full path to each file:
Sub ListAllFilesInAllFolders()
Dim MyPath As String, MyFolderName As String, MyFileName As String
Dim i As Integer, F As Boolean
Dim objShell As Object, objFolder As Object, AllFolders As Object, AllFiles As Object
Dim MySheet As Worksheet
On Error Resume Next
'************************
'Select folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "", 0, 0)
If Not objFolder Is Nothing Then
'MyPath =
MyPath = objFolder.self.Path & "\"
Else
Exit Sub
End If
Set objFolder = Nothing
Set objShell = Nothing
'************************
'List all folders
Set AllFolders = CreateObject("Scripting.Dictionary")
Set AllFiles = CreateObject("Scripting.Dictionary")
AllFolders.Add (MyPath), ""
i = 0
Do While i < AllFolders.Count
Key = AllFolders.keys
MyFolderName = Dir(Key(i), vbDirectory)
Do While MyFolderName <> ""
If MyFolderName <> "." And MyFolderName <> ".." Then
If (GetAttr(Key(i) & MyFolderName) And vbDirectory) = vbDirectory Then
AllFolders.Add (Key(i) & MyFolderName & "\"), ""
End If
End If
MyFolderName = Dir
Loop
i = i + 1
Loop
'List all files
For Each Key In AllFolders.keys
MyFileName = Dir(Key & "*.*")
'MyFileName = Dir(Key & "*.PDF") 'only PDF files
Do While MyFileName <> ""
AllFiles.Add (Key & MyFileName), ""
MyFileName = Dir
Loop
Next
'************************
'List all files in Files sheet
For Each MySheet In ThisWorkbook.Worksheets
If MySheet.Name = "Files" Then
Sheets("Files").Cells.Delete
F = True
Exit For
Else
F = False
End If
Next
If Not F Then Sheets.Add.Name = "Files"
'Sheets("Files").[A1].Resize(AllFolders.Count, 1) = WorksheetFunction.Transpose(AllFolders.keys)
Sheets("Files").[A1].Resize(AllFiles.Count, 1) = WorksheetFunction.Transpose(AllFiles.keys)
Set AllFolders = Nothing
Set AllFiles = Nothing
End Sub

Try using
With Sheets.Add
.Name = NewName
.Range("A1").Resize(AllFiles.Count, 1) = WorksheetFunction.Transpose(AllFiles.keys)
End With
Also, no need to to loop to test if the sheet exists. Use Error Handling instead
Dim FilesSheet as Worksheet
On Error Resume Next
Set FilesSheet = Thisworkbook.Sheets("Files")
On Error GoTo 0
If Not FilesSheet is Nothing then
F = True
Set FilesSheet = ThisWorkbook.Sheets.Add
FilesSheet.Name = NewName
Else
F = False
FilesSheet.Cells.Delete
End If
FilesSheet.Range("A1").Resize(AllFiles.Count, 1) = WorksheetFunction.Transpose(AllFiles.keys)
If you are creating this for End Users you may also want to build in functionality to check that the NewName they enter isn't too long (>31 Characters) for an Excel Sheet Name and doesn't contain any illegal characters (\ / * [ ] : ?)

Related

Assign variable for fixed path to FSO to scan folder and subfolders

I have created an excel macro, which loops through the different subfolders of a fixed parent folder. The parent folder directory does not change. I have found a code on the net, which first lets me choose the folder to scan, which is nice, but is awkward for my purpose, since I run the code several times and each time I have to choose the folder again.
Instead I would like to give the macro the fixed full path and do without the prompt to choose the folder. I have written the following code, but do not know how to adjust it to make it work the way I described. Could you give me some advise?
This is the code:
Dim MyPath As String, MyFolderName As String, MyFileName As String, strStartCell2 As String, strFolderToScan As String
Dim i As Integer
Dim F As Boolean
Dim objShell As Object, objFolder As Object, AllFolders As Object, AllFiles As Object, strFileFormat As Object, fso As Object
Dim MySheet As Worksheet
'Define variables and constants
Set strFileFormat = ThisWorkbook.Worksheets("Makro").Range("A6")
strStartCell2 = strStartCell
strFolderToScan = ThisWorkbook.Worksheets("Makro").Range("C4").Value & "\"
'Select folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Please select the folder you would like to scan", 0, 0)
If Not objFolder Is Nothing Then
MyPath = objFolder.self.Path & "\"
ThisWorkbook.Worksheets("Sheet1").Range("B3").Value = MyPath
Else
Exit Sub
End If
Set objFolder = Nothing
Set objShell = Nothing
'List all folders
Set AllFolders = CreateObject("Scripting.Dictionary")
Set AllFiles = CreateObject("Scripting.Dictionary")
AllFolders.Add (MyPath), ""
i = 0
Do While i < AllFolders.Count
Key = AllFolders.keys
MyFolderName = Dir(Key(i), vbDirectory)
Do While MyFolderName <> ""
If MyFolderName <> "." And MyFolderName <> ".." Then
If (GetAttr(Key(i) & MyFolderName) And vbDirectory) = vbDirectory Then
AllFolders.Add (Key(i) & MyFolderName & "\"), ""
End If
End If
MyFolderName = Dir
Loop
i = i + 1
Loop
'List all files
For Each Key In AllFolders.keys
MyFileName = Dir(Key & "*." & strFileFormat)
Do While MyFileName <> ""
AllFiles.Add (Key & MyFileName), ""
MyFileName = Dir
Loop
Next
'List all files in Files sheet
Sheets("Makro").Range(strStartCell2).Resize(AllFiles.Count, 1) = WorksheetFunction.Transpose(AllFiles.keys)
Set AllFolders = Nothing
Set AllFiles = Nothing
Probably this is simple, but i just can't figure out how to do it.
Thanks a lot in advance!
Oliver
This is the relevant part for selecting the folder
'Select folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Please select the folder you would like to scan", 0, 0)
If Not objFolder Is Nothing Then
MyPath = objFolder.self.Path & "\"
ThisWorkbook.Worksheets("Sheet1").Range("B3").Value = MyPath
Else
Exit Sub
End If
Set objFolder = Nothing
Set objShell = Nothing
Especially the objShell.BrowseForFolder is the part that asks you to browse for the folder. So you need to replace that to use strFolderToScan directly. We do that by using objShell.GetFolder(strFolderToScan) to get the folder from your path strFolderToScan.
But I recommend to check if the folder actually exists, so you do not run into errors:
'Select folder
Set objShell = CreateObject("Shell.Application")
If objShell.FolderExists(strFolderToScan) Then
MyPath = strFolderToScan
ThisWorkbook.Worksheets("Sheet1").Range("B3").Value = MyPath
Else
MsgBox "The folder '" & strFolderToScan & "' does not exist."
Exit Sub
End If
Set objShell = Nothing

Excel VBA Count number of rows in all files in folders and subfolders

I am trying to add a Do While loop to also output the number of rows in each file found in the folder specified. I am having trouble with it - I keep getting 0 rows with all versions of my code. Below is the original without the row count addition. I am hitting a wall and would love some direction.
Sub ListAllFilesInAllFolders()
Dim MyPath As String, MyFolderName As String, MyFileName As String
Dim i As Integer, F As Boolean
Dim objShell As Object, objFolder As Object, AllFolders As Object, AllFiles As Object
Dim MySheet As Worksheet
On Error Resume Next
'************************
'Select folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "", 0, 0)
If Not objFolder Is Nothing Then
MyPath = objFolder.self.Path & "\"
Else
Exit Sub
MyPath = "D:\Folder"
End If
Set objFolder = Nothing
Set objShell = Nothing
'************************
'List all folders
Set AllFolders = CreateObject("Scripting.Dictionary")
Set AllFiles = CreateObject("Scripting.Dictionary")
AllFolders.Add (MyPath), ""
i = 0
Do While i < AllFolders.Count
Key = AllFolders.keys
MyFolderName = Dir(Key(i), vbDirectory)
Do While MyFolderName <> ""
If MyFolderName <> "." And MyFolderName <> ".." Then
If (GetAttr(Key(i) & MyFolderName) And vbDirectory) = vbDirectory Then
AllFolders.Add (Key(i) & MyFolderName & "\"), ""
End If
End If
MyFolderName = Dir
Loop
i = i + 1
Loop
'List all files
For Each Key In AllFolders.keys
MyFileName = Dir(Key & "*.*")
'MyFileName = Dir(Key & "*.PDF") 'only PDF files
Do While MyFileName <> ""
AllFiles.Add (MyFileName), Key
MyFileName = Dir
Loop
Next
'************************
'List all files in Files sheet
For Each MySheet In ThisWorkbook.Worksheets
If MySheet.Name = "Files" Then
Sheets("Files").Cells.Delete
F = True
Exit For
Else
F = False
End If
Next
If Not F Then Sheets.Add.Name = "Files"
'Sheets("Files").[A1].Resize(AllFolders.Count, 1) = WorksheetFunction.Transpose(AllFolders.keys)
Sheets("Files").[A1].Resize(AllFiles.Count, 1) = WorksheetFunction.Transpose(AllFiles.Items)
Sheets("Files").[B1].Resize(AllFiles.Count, 1) = WorksheetFunction.Transpose(AllFiles.keys)
Set AllFolders = Nothing
Set AllFiles = Nothing
End Sub
I have tried:
Do While MyFileName <> ""
With MyFileName
If IsEmpty(.Range("a" & FirstDataRowInSourceFile)) Then
NumOfRecordsInSourceFile = 0
Else
NumOfRecordsInSourceFile = _
.Range(.Range("a" & FirstDataRowInSourceFile), .Range("a" &
FirstDataRowInSourceFile).End(xlDown)).Rows.Count
End If
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
On Error GoTo 0
'...
'...
Set AllFolders = CreateObject("Scripting.Dictionary")
Set AllFiles = CreateObject("Scripting.Dictionary")
AllFolders.Add (MyPath), ""
i = 0
Do While i < AllFolders.Count
'...
'...
Immediately after creating the dictionary the Count will be zero, so i < AllFolders.Count will be false and your loop never runs.
This should do it:
Sub ListAllFilesInAllFolders()
Dim i As Long, objFolder As Object, wsFiles As Worksheet
Dim colFiles As Collection, arrFiles, wb, MyPath As String
Set objFolder = CreateObject("Shell.Application").BrowseForFolder(0, "", 0, 0)
If Not objFolder Is Nothing Then
MyPath = objFolder.self.Path & "\"
Else
Exit Sub '????????
MyPath = "D:\Folder\"
End If
Set colFiles = GetMatchingFiles(MyPath, "*.csv")
Debug.Print "Found " & colFiles.Count & " matching files"
ReDim arrFiles(1 To colFiles.Count, 1 To 3) 'size output array
Application.ScreenUpdating = False
For i = 1 To colFiles.Count
Set wb = Workbooks.Open(colFiles(i), ReadOnly:=True)
arrFiles(i, 1) = wb.Path
arrFiles(i, 2) = wb.Name
arrFiles(i, 3) = wb.Sheets(1).UsedRange.Rows.Count
wb.Close False
Next i
Application.ScreenUpdating = True
On Error Resume Next 'ignore error if no match
Set wsFiles = ThisWorkbook.Sheets("Files")
On Error GoTo 0 'stop ignoring errors
If wsFiles Is Nothing Then
Set wsFiles = ThisWorkbook.Worksheets.Add()
wsFiles.Name = "Files"
End If
wsFiles.Cells.ClearContents
wsFiles.Range("a2").Resize(colFiles.Count, 3).Value = arrFiles
End Sub
'Search beginning at supplied folder root, including subfolders, for
' files matching the supplied pattern. Return all matches in a Collection
Function GetMatchingFiles(startPath As String, filePattern As String) As Collection 'of paths
Dim colFolders As New Collection, colFiles As New Collection
Dim fso As Object, fldr, subfldr, fl
Set fso = CreateObject("scripting.filesystemobject")
colFolders.Add startPath 'queue up root folder for processing
Do While colFolders.Count > 0 'loop until the queue is empty
fldr = colFolders(1) 'get next folder from queue
colFolders.Remove 1 'remove current folder from queue
With fso.getfolder(fldr)
For Each fl In .Files
If UCase(fl.Name) Like UCase(filePattern) Then 'check pattern
colFiles.Add fl.Path 'collect the full path
End If
Next fl
For Each subfldr In .subFolders
colFolders.Add subfldr.Path 'queue any subfolders
Next subfldr
End With
Loop
Set GetMatchingFiles = colFiles
End Function

How do I read the metadata information from a closed workbook using Excel VBA?

I'm trying to copy files from one location to another based upon either the Title or Tags metadata of a file but I cannot seem to be able to do that and I'm not sure why.
This is my code:
Path = "C:\Users\blahblah"
destination = "C:\Users\blahblah\blibbityblah"
Set FSO = CreateObject("Scripting.filesystemobject")
Set obj_folder = FSO.GetFolder(Path)
For Each obj_subfolder In obj_folder.SubFolders
For Each file In obj_subfolder.FILES
If InStr(1, file.BuiltInDocumentProperties("title"), "Blah") Then
Debug.Print file.BuiltInDocumentProperties("title")
Call FSO.CopyFile(file.Path, FSO.BuildPath(destination, file.Name))
End If
Next file
Next obj_subfolder
This breaks right here and I get an error message stating that the object doesn't support the property or method:
If InStr(1, file.BuiltInDocumentProperties("title"), "Blah") Then
Additionally, I've tried using a shell object to identify the tags of the workbook as so:
Path = "C:\Users\blahblah"
destination = "C:\Users\blahblah\blibbityblah"
Set FSO = CreateObject("Scripting.filesystemobject")
Set obj_folder = FSO.GetFolder(Path)
Set shell_object = CreateObject("shell.application")
Set dir_object = shell_object.Namespace(CVar(Path))
For Each obj_subfolder In obj_folder.SubFolders
For Each file In obj_subfolder.FILES
If InStr(1, file.Name, ".xlsx") Then
Debug.Print dir_object.getdetailsof(file, 18)
'Call FSO.CopyFile(file.Path, FSO.BuildPath(destination, file.Name))
End If
Next file
Next obj_subfolder
The tag data in my file when I look manually says "Blah" but when I debug.print it only reads as "Tags". Can someone please steer me in the right direction here? Thank you.
EDIT
I have also tried appending .Value to the end of the .BuiltInDocumentsProperties with the same outcome.
I have also downloaded and installed the Dsofile.dll file and added the reference with the same result.
Here is the example showing how to retrieve details of a file with Shell.Application:
Option Explicit
Sub Test()
Dim oDetails, sName
Set oDetails = GetDetails("C:\Users\blahblah\blibbityblah\test.xlsx")
If oDetails.Exists("Tags") Then Debug.Print oDetails("Tags")
If oDetails.Exists("Title") Then Debug.Print oDetails("Title")
Debug.Print String(40, "-")
For Each sName In oDetails
Debug.Print sName & " = " & oDetails(sName)
Next
End Sub
Function GetDetails(sPath)
Dim sFolderName, sFileName, oShell, oFolder, oFile, oDetails, i, sName, sValue
SplitFullPath sPath, sFolderName, sFileName
Set oShell = CreateObject("Shell.Application")
Set oFolder = oShell.Namespace(sFolderName)
Set oFile = oFolder.ParseName(sFileName)
Set oDetails = CreateObject("Scripting.Dictionary")
For i = 0 To 511
sName = oFolder.GetDetailsOf(oFolder.Items, i)
sValue = oFolder.GetDetailsOf(oFile, i)
If sName <> "" And sValue <> "" Then oDetails(sName) = sValue
Next
Set GetDetails = oDetails
End Function
Sub SplitFullPath(sPath, sFolderName, sFileName)
With CreateObject("Scripting.FileSystemObject")
If Not .FileExists(sPath) Then Exit Sub
sFolderName = .GetParentFoldername(sPath)
sFileName = .GetFileName(sPath)
End With
End Sub

How to define path to a folder?

I have code for listing folders, sub folders and filenames. I have to choose a folder by clicking the code.
How it is possible to define path? I have tried to uncomment MyPath but it didn't work.
My path: "\infra\Services\turb"
Sub ListAllFilesInAllFolders()
Dim MyPath As String, MyFolderName As String, MyFileName As String
Dim i As Integer, F As Boolean
Dim objShell As Object, objFolder As Object, AllFolders As Object, AllFiles As Object
Dim MySheet As Worksheet
On Error Resume Next
'************************
'Select folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "", 0, 0)
If Not objFolder Is Nothing Then
'MyPath = "\\infra\Services\turb"
MyPath = objFolder.self.Path & "\"
Else
Exit Sub
'MyPath = "\\infra\Services\turb"
End If
Set objFolder = Nothing
Set objShell = Nothing
'************************
'List all folders
Set AllFolders = CreateObject("Scripting.Dictionary")
Set AllFiles = CreateObject("Scripting.Dictionary")
AllFolders.Add (MyPath), ""
i = 0
Do While i < AllFolders.Count
Key = AllFolders.keys
MyFolderName = Dir(Key(i), vbDirectory)
Do While MyFolderName <> ""
If MyFolderName <> "." And MyFolderName <> ".." Then
If (GetAttr(Key(i) & MyFolderName) And vbDirectory) = vbDirectory Then
AllFolders.Add (Key(i) & MyFolderName & "\"), ""
End If
End If
MyFolderName = Dir
Loop
i = i + 1
Loop
'List all files
For Each Key In AllFolders.keys
MyFileName = Dir(Key & "*.*")
'MyFileName = Dir(Key & "*.PDF") 'only PDF files
Do While MyFileName <> ""
AllFiles.Add (Key & MyFileName), ""
MyFileName = Dir
Loop
Next
'************************
'List all files in Files sheet
For Each MySheet In ThisWorkbook.Worksheets
If MySheet.Name = "Files" Then
Sheets("Files").Cells.Delete
F = True
Exit For
Else
F = False
End If
Next
If Not F Then Sheets.Add.Name = "Files"
'Sheets("Files").[A1].Resize(AllFolders.Count, 1) = WorksheetFunction.Transpose(AllFolders.keys)
Sheets("Files").[A1].Resize(AllFiles.Count, 1) = WorksheetFunction.Transpose(AllFiles.keys)
Set AllFolders = Nothing
Set AllFiles = Nothing
End Sub
---------------- EDIT ---------------------
Same path in another code that is working. This code is doing quite the same but I don't like the output of listing folders.
Option Explicit
Private iColumn As Integer
Sub TestListFolders(strPath As String, Optional bFolders As Boolean = True)
Application.ScreenUpdating = False
Cells.Delete
Range("A1").Select
iColumn = 1
' add headers
With Range("A1")
.Formula = "Folder contents: " & strPath
.Font.Bold = True
.Font.Size = 12
End With
If Right(strPath, 1) <> "\" Then
strPath = strPath & "\"
End If
ListFolders strPath, bFolders
Application.ScreenUpdating = True
End Sub
ListFolders:
Sub ListFolders(SourceFolderName As String, IncludeSubfolders As Boolean)
' lists information about the folders in SourceFolder
' example: ListFolders "C:\", True
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.Folder, SubFolder As Scripting.Folder
Dim r As Long
Dim strfile As String
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
'line added by dr for repeated "Permission Denied" errors
On Error Resume Next
iColumn = iColumn + 1
' display folder properties
ActiveCell.Offset(1).Select
With Cells(ActiveCell.Row, iColumn)
.Formula = SourceFolder.Name
.Font.ColorIndex = 11
.Font.Bold = True
.Select
End With
strfile = Dir(SourceFolder.Path & "\*.*")
If strfile <> vbNullString Then
ActiveCell.Offset(0, 1).Select
Do While strfile <> vbNullString
ActiveCell.Offset(1).Select
ActiveCell.Value = strfile
strfile = Dir
Loop
ActiveCell.Offset(0, -1).Select
End If
Cells(r, 0).Formula = SourceFolder.Name
Cells(r, 3).Formula = SourceFolder.Size
Cells(r, 4).Formula = SourceFolder.SubFolders.Count
Cells(r, 5).Formula = SourceFolder.Files.Count
Cells(r, 6).Formula = SourceFolder.ShortName
Cells(r, 7).Formula = SourceFolder.ShortPath
If IncludeSubfolders Then
For Each SubFolder In SourceFolder.SubFolders
ListFolders SubFolder.Path, True
iColumn = iColumn - 1
Next SubFolder
Set SubFolder = Nothing
End If
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub
Create new worksheet and list sub folders there:
Sub ListAllFilesTurb()
Dim WS As Worksheet
Set WS = Sheets.Add
Sheets.Add.Name = "Turb"
TestListFolders "\\infra\Services\turb"
End Sub
Get rid of the objFolder and objShell (and any dependent conditional code, etc.). Then you should be able to hardcode MyPath. As presently written, this code is using the objShell to browse.
Get rid of this:
'Select folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "", 0, 0)
If Not objFolder Is Nothing Then
'MyPath = "\\infra\Services\turb"
MyPath = objFolder.self.Path & "\"
Else
Exit Sub
'MyPath = "\\infra\Services\turb"
End If
Set objFolder = Nothing
Set objShell = Nothing
Replace with this:
' Define hard-coded folder:
MyPath = "\\infra\Services\turb" '# Modify as needed
NOTE: It is important that the MyPath end with a backslash character, while you can hardcode that on the same line, e.g.:
MyPath = "\\infra\Services\turb\"
It may be best to add a check for it (similar to the original code) just in case you forget, so:
MyPath = "\\infra\Services\turb"
'### Ensure the path ends with a separator:
MyPath = MyPath & IIf(Right(MyPath, 1) = Application.PathSeparator, "", Application.PathSeparator)

How do i fix a Compile error/ Syntax error?

I've tried understanding the logic of the loop and my sheet. I'm trying to get .pdf files transferred from a folder to another based off of what criteria is in an excel file, or column H = YES.
I get a syntax error down at the bottom of the code
**objFSO.CopyFile Source:=OldPath & Range("H"&CStr(iRow)).Value & sFileType,
Destination:=NewPath**
Sub Rectangle1_Click()
Dim iRow As Integer
Dim OldPath As String
Dim NewPath As String
Dim sFileType As String
Dim bContinue As Boolean
bContinue = True
iRow = 2
' The Source And Destination Folder With Path
OldPath = "C:\Users\bucklej\Desktop\Spec\"
NewPath = "C:\Users\bucklej\Desktop\Dest\"
sFileType = ".pdf"
'Loop Through Column "H" To Pick The Files
While bContinue
If Len(Range("H" & CStr(iRow)).Value) = Yes Then
MsgBox "Files Copied"
bContinue = False
Else
Range("H" & CStr(iRow)).Value = "No"
Range("H" & CStr(iRow)).Font.Bold = False
If Trim(NewPath) <> "" Then
Set objFSO = CreateObject("scripting.filesystemobject")
'Check if destination folder exsists
If objFSO.FolderExists(NewPath) = False Then
MsgBox NewPath & "Does Not Exist"
Exit Sub
End If
'Using CopyFile Method to copy the files
Set objFSO = CreateObject("scripting.filesystemobject")
objFSO.CopyFile Source:=OldPath & Range("H"&CStr(iRow)).Value & sFileType,
Destination:=NewPath
End If
End If
End If
iRow = iRow + 1
Wend
End Sub
CORRECT CODE listed below:
Sub Rectangle1_Click()
Dim OldPath As String, NewPath As String
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
'~~> File location bucklej
OldPath = "C:\Users\bucklej\Desktop\Specs\"
NewPath = "C:\Users\bucklej\Desktop\Dest\"
Set ws = ThisWorkbook.Sheets("Specification Listing")
Range("A2").Activate '<--- to make sure we're starting at the right spot
For i = 2 To 1000
If Cells(i, 8).Value = "YES" Then '<--- correct, 8th column over
On Error GoTo ErrHandle
fso.CopyFile OldPath & Cells(i, 1).Value & ".pdf", NewPath
End If
Next i
ErrHandle:
ws.Cells(i, 11).Value = "File Not Found"
Resume Next
End Sub
looking back at the second duplicate question and the snippet of code provided as an answer I see you said you were getting an error msg and the conversation went dead. Expanding on that answer I was able to get the following to work using a test.txt. You should be able to tweak this to your needs.
Sub Rectangle1_Click()
Dim OldPath As String, NewPath As String
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
'~~> File location
OldPath = "C:\Users\me\Desktop\"
NewPath = "C:\Users\me\Desktop\Test\"
For i = 1 To 1000
If Cells(i, 2).Value = "yes" Then
fso.copyfile OldPath & Cells(i, 3).Value & ".txt", NewPath
End If
Next i
End Sub
UPDATE: I think (maybe) what the issue is is that since it's doing nothing the right sheet isn't being referenced. Paste this updated code in the 'ThisWorkbook' and rename the sheet name in the code.
Sub Rectangle1_Click()
Dim OldPath As String, NewPath As String
Dim ws As Worksheet
Dim wb As Workbook
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Set wb = ActiveWorkbook
Set ws = wb.Worksheets("Test") <--rename to the sheet that has the parts numbers
'~~> File location
OldPath = "C:\Users\bucklej\Desktop\Spec\"
NewPath = "C:\Users\bucklej\Desktop\Dest\"
For i = 1 To 1000
If ws.Cells(i, 2).Value = "YES" Then
fso.CopyFile OldPath & Cells(i, 3).Value & ".pdf", NewPath
End If
Next i
End Sub
again, feel free to email me.
UPDATE: Final version with err handling thrown in
Sub Rectangle1_Click()
Dim OldPath As String, NewPath As String
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
'~~> File location bucklej
OldPath = "C:\Users\me\Desktop\Specs\"
NewPath = "C:\Users\me\Desktop\Dest\"
Set ws = ThisWorkbook.Sheets("Specification Listing")
Range("A2").Activate
For i = 2 To 1000
If Cells(i, 8).Value = "YES" Then
On Error GoTo ErrHandle
fso.CopyFile OldPath & Cells(i, 1).Value & ".pdf", NewPath
End If
Next i
ErrHandle:
ws.Cells(i, 11).Value = "File Not Found"
Resume Next
End Sub

Resources