I have created a code to give me path and there names for all the files in a folder to excel.
But my problem is its giving me file names of all the files in that folder. I just want to search and retrieve names of only pdf files to excel.
Here is what I have:
Sub Example1()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder(Range("H1").Value)
i = 1
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'print file path
Cells(i + 3, 2) = objFile.Path
i = i + 1
Next objFile
End Sub
As per the comments. You need to test if the last three characters are 'pdf'
So in your for loop add the if statement
For Each objFile In objFolder.Files
if right(objFile.Path,3) = "pdf" then
'print file path
Cells(i + 3, 2) = objFile.Path
i = i + 1
end if
Next objFile
This should work:
Sub Find_PDF()
Dim FileToCheck As String, FilePath As String, FileWildCard As String
FilePath = "c:\YOUR FILE PATH\"
FileWildCard = "*.pdf"
FileToCheck = Dir(FilePath & FileWildCard)
Do While FileToCheck <> ""
i = i + 1
Sheets("Sheet1").Range("A" & i).Value = FileToCheck
FileToCheck = Dir()
Loop
End Sub
This is not a free coding service but i would answer this anyway:
For Each objFile In objFolder.Files
if right(objFile.Path,3) = "pdf" then
'print file path
Cells(i + 3, 2) = objFile.Path
i = i + 1
end if
msgbox ("Answer are here dont troll on someone")
Next objFile
Related
company moved folders to onedrive however some people still using local drives, so I need help to check the folder is exist on one drive or not. below code for using for onedrive. I cannot create if condition on this.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Environ("UserProfile") & "\OneDrive - company name\Pictures\Camera Roll")
i = 1
For Each objFile In objFolder.Files
Range(Cells(i + 1, 1), Cells(i + 1, 1)).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
objFile.Path, _
TextToDisplay:=objFile.Name
you could set objFolder before the loop
Set objFSO = CreateObject("Scripting.FileSystemObject")
With objFSO
If .folderexists(Environ("UserProfile") & "\OneDrive - company name\Pictures\Camera Roll") Then
Set objFolder = objFSO.GetFolder(Environ("UserProfile") & "\OneDrive - company name\Pictures\Camera Roll")
Else
Set objFolder = objFSO.GetFolder(Environ("UserProfile") & "\picture\camera roll")
End If
End With
Try the next code, please. It will create hyperlinks for both cases, if both of them exist:
Sub CheckOneDriveVersusLocalToHyperlink()
Dim objFSO As Object, objFolder As Object, objFile As Object, sh As Worksheet, i As Long
Const OneDrPath As String = "\OneDrive - company name\Pictures\Camera Roll"
Const LocalPath As String = "c:\users\userprofile\picture\camera roll"
Set sh = ActiveSheet
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(Environ("UserProfile") & OneDrPath) Then
Set objFolder = objFSO.GetFolder(Environ("UserProfile") & OneDrPath)
i = 1
For Each objFile In objFolder.Files
ActiveSheet.Hyperlinks.Add sh.cells(i + 1, 1), Address:= _
objFile.Path, TextToDisplay:=objFile.Name
i = i + 1
Next
End If
If objFSO.FolderExists(LocalPath) Then
Set objFolder = objFSO.GetFolder(LocalPath)
i = 1
For Each objFile In objFolder.Files
ActiveSheet.Hyperlinks.Add sh.cells(i + 1, 3), Address:= _
objFile.Path, TextToDisplay:=objFile.Name
i = i + 1
Next
End If
End Sub
Please, take care to use your real paths. I do not think that the OneDrive one is correct in the way you show it. Is it a path on the intranet?
It will create hyperlinks from OneDrive in A:A column, and ones for local path in C:C column.
Of course, if you need only to create hyperlinks for the OneDrive folder (only in case it exists), you just delete the last part treating the local path. Or use Else instead of End If ... If, in case you need the hyperlink for the local path, only in case that the first one does not exist.
Please advise - I wrote a code in VBA that iterates through files in certain directory, rename them, and write the status to Excel.
I would like to edit the code so that if the command Name returns error (For example if NewFileName already exists), then the parameter status would be "Fail", and continue to the next iteration. Could anyone help me how to do so?
Sub RenameFiles()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
Dim directory As String
Dim OldFileName As String
Dim NewFileName As String
Dim illegal As String
Dim legal As String
Dim status As String
directory = (ThisWorkbook.Worksheets(4).Range("G6").Value) & "\"
illegal = (ThisWorkbook.Worksheets(4).Range("G8").Value)
legal = (ThisWorkbook.Worksheets(4).Range("G10").Value)
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder(directory)
i = 1
'loops through each file in the directory and rename them
For Each objFile In objFolder.Files
OldFileName = objFile.Name
NewFileName = Replace(OldFileName, illegal, legal)
'Rename
Name directory & OldFileName As directory & NewFileName
'print old file name
Cells(i + 1, 1) = OldFileName
'print new file name
Cells(i + 1, 2) = NewFileName
'print new file path
Cells(i + 1, 3) = directory & NewFileName
'print status
If (OldFileName <> NewFileName) Then
status = "Success"
'Ifelse ()
Else
status = "No Change"
End If
Cells(i + 1, 3) = status
i = i + 1
Next objFile
End Sub
Im trying to come up with a piece of script that will allow me to copy 100 files from one folder and create a new folder based on the first file and last file name and then move those 100 files to that folder.
After moving those files, i want it to display the folders in a userform listbox as clickable items.
For example, each item in the listbox will be a folder, if i double click on a folders name it will display all the contents of the file (of each of 100 files) in a sheet i've set up.
I haven't been able to test this code yet, all i've done for the past week was research and rewrite the code over and over until i could understand it properly before adding it to the program. So there's bound to be some or more errors along the way.
What i did notice was the "objFile.CopyFile Folderpath & FCount & "_" & LCount" piece of code that doesnt specify which files could be copied specifically. For example, i want it to start at the first file and start coping the first 100 files, when the code is executed again, it will start at file 101 and copy the next 100 files. If there's way to ensure that it wouldnt keep copying the first 100 files, that would be awesome!
Sub Main()
'====CHECK IF THERE'S 100 FILES====
Dim filename, folderpath, path As String
Dim count As Integer
Dim FCount, LCount, FlagCount, IntCount As Integer
Dim objFSO As Object
Dim obj As Object
FCount = 0 ' First File name
LCount = 0 'Last file name
count = 0 'file count
FlagCount = Sheets("Flag Sheet").Range("A2").Value
folderpath = "Work\Big Book\" '==================Location Of The Book
path = folderpath & "*.xls"
filename = Dir(path)
Do While filename <> ""
count = count + 1
filename = Dir(path)
Loop
If count < 100 Then
'====CREATE A FOLDER FOR THE FILES====
If FlagCount <> "" Then '====If there is a flag count, it will create a folder based on the last number it was used
FCount = FlagCount + 1
LCount = FlagCount + 101
MkDir folderpath & FCount & "_" & LCount
Else '=======================else if there isnt one, it will use the first file name to create the folder
FCount = IntCount + 1
LCount = IntCount + 100
MkDir folderpath & FCount & "_" & LCount
End If
'====MOVE 100 FILES TO FOLDER====
For Each objFile In objFSO.GetFolder(path)
If FlagCount <> "" Then '====================if theres a flag count it will move the files starting after the flag count + 101
objFile.CopyFile folderpath & FCount & "_" & LCount
IntCount = FlagCount + 1
If IntCount = FlagCount + 100 Then Exit For
Else '======================================else it will just move the first 100 files
objFile.CopyFile folderpath & FCount & "_" & LCount
IntCount = IntCount + 1
If IntCount = IntCount + 100 Then Exit For
End If
Next
End If
Else
'===Do Nothing===
End If
End Sub
'=====Display Folders In Listbox=====
'====Display Folder Items In Book====
'Call the function
DisplayFoldersInListBox folderpath & FCount & "_" & LCount, Me.Listbox1
Sub Button_Click()
For Each File in Folderpath & FCount & "_" & LCount & "\" & Listbox.value
'[INSERT BIG BOOK CODE]
Next
End Sub
Private Sub DisplayFoldersInListBox(ByVal strRootFolder As String, ByRef lbxDisplay As MSForms.ListBox)
Dim fso As Object
Dim fsoRoot As Object
Dim fsoFolder As Object
'Make sure that root folder contains trailing backslash
If Right$(strRootFolder, 1) <> "\" Then strRootFolder = strRootFolder & "\"
'Get reference to the FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
'Get the root folder
Set fsoRoot = fso.GetFolder(strRootFolder)
'Clear the listbox
lbxDisplay.Clear
'Populate the listbox with subfolders of Root
For Each fsoFolder In fsoRoot.SubFolders
lbxDisplay.AddItem fsoFolder.Name
Next fsoFolder
'Clean up
Set fsoRoot = Nothing
Set fso = Nothing
End Sub
This link: Copy only the first file of a folder VBA
Seems to be the answer for the coping of the files, but im not entirely sure how to add it to my script. Can anyone help me out?
Back to the basics:
CopyXNumberOfFiles:Sub
Sub CopyXNumberOfFiles(SourceFolder As String, TargetFolder As String, Optional MaxNumFiles As Long = 100)
Dim fso As Object, objFile As Object
Dim count As Long
Dim Path As String
Set fso = CreateObject("Scripting.FileSystemObject")
If Not Right(SourceFolder, 1) = "\" Then SourceFolder = SourceFolder & "\"
If Not Right(TargetFolder, 1) = "\" Then TargetFolder = TargetFolder & "\"
For Each objFile In fso.GetFolder(SourceFolder).Files
If objFile.Path Like "*.xls?" Then
Path = TargetFolder & objFile.Name
If Len(Dir(Path)) = 0 Then
FileCopy objFile.Path, Path
count = count + 1
If count >= MaxNumFiles Then Exit For
End If
End If
Next
End Sub
Usage
CopyXNumberOfFiles "C:\","C:\Data"
Addendum
This function will copy the files over and return an array of the new file paths.
Function getCopyXNumberOfFiles(SourceFolder As String, TargetFolder As String, Optional MaxNumFiles As Long = 100) As String()
Dim fso As Object, objFile As Object
Dim count As Long, n As Long
Dim Path As String
Dim data() As String, results() As String
ReDim data(1 To 2, 1 To MaxNumFiles)
Set fso = CreateObject("Scripting.FileSystemObject")
If Not Right(SourceFolder, 1) = "\" Then SourceFolder = SourceFolder & "\"
If Not Right(TargetFolder, 1) = "\" Then TargetFolder = TargetFolder & "\"
For Each objFile In fso.GetFolder(SourceFolder).Files
If objFile.Path Like "*.xls?" Then
Path = TargetFolder & objFile.Name
If Len(Dir(Path)) = 0 Then
FileCopy objFile.Path, Path
count = count + 1
data(1, count) = objFile.Path
data(2, count) = Path
If count >= MaxNumFiles Then Exit For
End If
End If
Next
ReDim Preserve results(1 To count, 1 To 2)
For n = 1 To count
results(n, 1) = data(1, n)
results(n, 2) = data(2, n)
Next
getCopyXNumberOfFiles = results
End Function
Usage
Column 1 has the original paths and column 2 has the new paths.
Dim Files() as String, firstFilePath as String, lastFilePath as String
Files = getCopyXNumberOfFiles("C:\", "C:\New Folder\", 100)
Original Paths
firstFilePath = Files(1, 1)
lastFilePath = Files(Ubound(Files), 1)
New Paths
firstFilePath = Files(1, 2)
lastFilePath = Files(Ubound(Files), 2)
This question already has answers here:
Recursively access subfolder files inside a folder
(2 answers)
Closed 6 years ago.
So I want to make a .vbs that edits all .txt in a folder. This the code I used, and the folder is C:\test folder.
Const ForReading = 1
Const ForWriting = 2
newline = ""
line = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\test folder\"
Dim lineCount : lineCount = 0
Dim firstContent : firstContent = ""
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
If LCase(objFSO.GetExtensionName(objFile)) = "txt" Then
lineCount = 0
firstContent = ""
FileName = objStartFolder & objFile.Name
Set objStream = objFSO.OpenTextFile(FileName, ForReading)
Do Until objStream.AtEndOfStream
lineCount = lineCount + 1
firstContent = firstContent & objStream.ReadLine & vbCrLf
If lineCount = line Then
firstContent = firstContent & newline & vbCrLf
End If
Loop
Set objStream = objFSO.OpenTextFile(FileName, ForWriting)
objStream.WriteLine firstContent
objStream.Close
End If
Next
It works. and changes all the text files to what I want them to say, but when I made a folder in C:\test folder called SF (C:\test folder\SF), all of the text files in SF don't change. How do I get it to work with subfolders?
Recursion is a function calling itself. It is used to walk trees.
ProcessFolder DirName
Sub ProcessFolder(FolderPath)
' On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
msgbox Thing.Name & " " & Thing.path
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub
I am building this index of files in a directory.
Column 1 with folder name(s), Column 2 with filename
I have managed to get the actual filename and hyperlinking the filename already.
But I have problems listing the path to the file in column 1, using a relative path including its subfolders.
Say I have the following folder:
"C:\users\ME\Documents"
Inside that folder there are many subfolders.
What I want to achieve is a string that list the path to that actual subfolder.
Example:
"C:\users\ME\Documents\Subfolder1\Subfolder2\CharlieSheen.pdf"
Column 1 (A5) = Subfolder1\Subfolder2\
Column 2 (B5) = CharlieSheen.pdf
As I said I have control over column 2.
The script I am using already is
Private Function GetAllFiles(ByVal strpath As String, _
ByVal intRow As Integer, ByRef objFSO As Object) As Integer
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer`
i = intRow - ROW_FIRST + 1
Set objFolder = objFSO.Getfolder(strpath)
For Each objFile In objFolder.Files
'print file path
Cells(i + ROW_FIRST - 1, 1) = objFolder.Name
i = i + 1
Next objFile
GetAllFiles = i + ROW_FIRST - 1
End Function
I figured out that changing
Cells(i + ROW_FIRST - 1, 1) = objFolder.Name
into Cells(i + ROW_FIRST - 1, 1) = objFSO.Getfolder(".") returned exactly what I wanted to remove from the first string!
So I basically want to write a script that says:
Cells(i + ROW_FIRST - 1, 1) = objFolder.Name - objFSO.Getfolder(".")
But I need help since that command obviously doesn't work.
There might be a totally different approach to this, but since my macro already have a lot of code, using Trim or Replace or similar would be the easiest?
Edit:
There's also a function in my script named "GetAllFolders".
Maybe I can call on that in some way to implement the string I want?
Private Sub GetAllFolders(ByVal strFolder As String, _
ByRef objFSO As Object, ByRef intRow As Integer)
Dim objFolder As Object
Dim objSubFolder As Object
'Get the folder object
Set objFolder = objFSO.GetFolder(strFolder)
'loops through each file in the directory and
'prints their names and path
For Each objSubFolder In objFolder.subfolders
intRow = GetAllFiles(objSubFolder.Path, _
intRow, objFSO)
'recursive call to to itsself
Call GetAllFolders(objSubFolder.Path, _
objFSO, intRow)
Next objSubFolder
End Sub
What about
Cells(i + ROW_FIRST - 1, 1) = Replace$(objFolder.Name, CStr(objFSO.Getfolder(".")), vbNullString)