The below code works until used on a directory with paths over 255 characters.
Runtime error 13 mismatch occurs.
I have a hunch that the built in .transpose operation does not support 255 characters.
How can I manually do this operation?
My other crawler is not recursive, so I have never had this issue.
At this point I'm wondering if recursive efficiency is worth it.
Also the UNC path output is a requirement, shortening it to drive letter is a not an option.
Option Explicit
Sub CreateFileStructureReport()
Dim Msheet As String
Dim minNum As Integer
Msheet = Application.ActiveWorkbook.Path
Application.Calculation = xlCalculationManual
Call GetFileList
Application.Calculation = xlCalculationAutomatic
Range("A2").Select
End Sub
Sub GetFileList()
Dim ans As String
Dim strFolder As String
Dim objFSO As Object
Dim objFolder As Object
Dim myResults As Variant
Dim lCount As Long
ans = Application.CommandBars("Web").Controls("Address:").Text
If ans = "" Then Exit Sub
ans = Left(ans, InStrRev(ans, "\"))
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(ans)
'the variable dimension has to be the second one
ReDim myResults(0 To 6, 0 To 0)
' place make some headers in the array
myResults(0, 0) = "Extension"
myResults(1, 0) = "Bytes"
myResults(2, 0) = "Created"
myResults(3, 0) = "Modified Info"
myResults(4, 0) = "Last Accessed"
myResults(5, 0) = "File Name"
myResults(6, 0) = "\\Root\T01\T02\T03\T04\T05\T06\T07\T08\T09\T10\T11\T12\T13\T14\T15\T16\T17\T18\T19\T20"
'Send the folder to the recursive function
FillFileList objFolder, myResults, lCount
' Dump these to a worksheet
DumpToWorksheet myResults
'tidy up
Set objFSO = Nothing
End Sub
Private Sub FillFileList(objFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)
Dim i As Integer
Dim objFile As Object
Dim fsoSubFolder As Object
Dim fsoSubFolders As Object
'load the array with all the files
For Each objFile In objFolder.Files
lCount = lCount + 1
ReDim Preserve myResults(0 To 6, 0 To lCount)
myResults(0, lCount) = objFile.Type
myResults(1, lCount) = objFile.Size
myResults(2, lCount) = objFile.DateCreated
myResults(3, lCount) = objFile.DateLastModified
myResults(4, lCount) = objFile.DateLastAccessed
myResults(5, lCount) = objFile.Name
myResults(6, lCount) = objFile.Path
Next objFile
'recursively call this function with any subfolders
Set fsoSubFolders = objFolder.SubFolders
DoEvents
For Each fsoSubFolder In fsoSubFolders
FillFileList fsoSubFolder, myResults, lCount
Next fsoSubFolder
End Sub
Private Sub DumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
Dim iSheetsInNew As Integer
Dim sh As Worksheet, wb As Workbook
Dim myColumnHeaders() As String
Dim l As Long, NoOfRows As Long
If mySh Is Nothing Then
'make a workbook if we didn't get a worksheet
iSheetsInNew = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1
Set wb = Application.Workbooks.Add
Application.SheetsInNewWorkbook = iSheetsInNew
Set sh = wb.Sheets(1)
Else
Set mySh = sh
End If
'since we switched the array dimensions, have to transpose
With sh
Range(.Cells(1, 1), .Cells(UBound(varData, 2) + 1, UBound(varData, 1) + 1)) = _
Application.WorksheetFunction.Transpose(varData)
.UsedRange.Columns.AutoFit
End With
Set sh = Nothing
Set wb = Nothing
End Sub
Related
I have the following code, but am looking to change it so the output only provides the first part of the file name. The file names are in the following format. ZipCode_Name_Date. I only want the part of the name which states the Zipcode to print out.
Option Explicit
Sub GetFileDetails()
Dim objFSO As Scripting.FileSystemObject
Dim objFolder As Scripting.Folder
Dim objFile As Scripting.File
Dim nextRow As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("")
nextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
For Each objFile In objFolder.Files
Cells(nextRow, 1) = objFile.Name
nextRow = nextRow + 1
Next
End Sub
Please, replace Cells(nextRow, 1) = objFile.Name with Cells(nextRow, 1) = Split(objFile.Name, "_")(0).
Extract FileParts
If you write it as a function...
Option Explicit
Function GetFirstFileNamePart( _
ByVal FolderPath As String, _
ByVal FilePartsDelimiter As String) _
As Variant
Dim fsoFolder As Object
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(FolderPath) Then Exit Function
Set fsoFolder = .GetFolder(FolderPath)
End With
Dim fCount As Long: fCount = fsoFolder.Files.Count
If fCount = 0 Then Exit Function
Dim Data As Variant: ReDim Data(1 To fCount, 1 To 1)
Dim fsoFile As Object
Dim n As Long
For Each fsoFile In fsoFolder.Files
n = n + 1
' This is the place to modify what to return.
' 0 means the part before the first found delimiter.
Data(n, 1) = Split(fsoFile.Name, FilePartsDelimiter)(0)
Next fsoFile
GetFirstFileNamePart = Data
End Function
... you can easily utilize it in the calling procedure (adjust the constants):
Sub GetFirstFileNamePartTEST()
' Constants
Const FilePartsDelimiter As String = "_"
Dim FolderPath As String
FolderPath = Environ("OneDrive") & "\Documents\"
Const dCol As String = "A"
' Using the function, write the data to a 2D one-based one-column array.
Dim Data As Variant
Data = GetFirstFileNamePart(FolderPath, FilePartsDelimiter)
' Validate.
If IsEmpty(Data) Then
MsgBox "No files found.", vbExclamation
Exit Sub
End If
' Write the data to the range.
Dim ws As Worksheet: Set ws = ActiveSheet ' be more specific
Dim dCell As Range
Set dCell = ws.Cells(ws.Rows.Count, dCol).End(xlUp).Offset(1)
Dim drg As Range: Set drg = dCell.Resize(UBound(Data, 1), UBound(Data, 2))
drg.Value = Data
MsgBox "First filename parts copied.", vbInformation
End Sub
I am a VBA novice but have been able to modify the below code to insert images in my spreadsheet based on cell values as long as the images are in the specific folder. How would I go about changing the code so that it searches all the sub folders within the directory? Any help would be greatly appreciated.
Public Sub Add_Pics_Example()
Dim oCell As Range
Dim oRange As Range
Dim oActive As Worksheet
Dim sPath As String
Dim sFile As String
Dim oShape As Shape
Worksheets("Range").Activate
sPath = "Z:\Pictures\Product Images\"
ActiveSheet.DrawingObjects.Select
Selection.Delete
Set oActive = ActiveSheet
Set oRange = oActive.Range("B4:bz4")
On Error Resume Next
For Each oCell In oRange
sFile = oCell.Value & ".jpg"
Set oShape = oActive.Shapes.AddPicture(sPath & sFile, False, True, _
oCell.Offset(-3, 0).Left + 30, oCell.Offset(-3, 0).Top + 3, 60, 60)
Next oCell
On Error GoTo 0
Application.ScreenUpdating = True
End Sub
Untested but should be pretty close:
Public Sub Add_Pics_Example()
Dim oCell As Range
Dim oRange As Range
Dim wsActive As Worksheet
Dim sFile As String
Dim dictFiles As Object
Set wsActive = Worksheets("Range")
wsActive.DrawingObjects.Delete
'get all the image files first
Set dictFiles = AllFilesbyName("Z:\Pictures\Product Images\", "*.jpg")
For Each oCell In wsActive.Range("B4:BZ4")
sFile = oCell.Value & ".jpg"
'do we have this file ?
If dictFiles.exists(sFile) Then
wsActive.Shapes.AddPicture dictFiles(sFile), False, True, _
oCell.Offset(-3, 0).Left + 30, _
oCell.Offset(-3, 0).Top + 3, 60, 60
End If
Next oCell
End Sub
'starting at startFolder, return a dictionary mapping file names to
' full paths (note doesn't handle >1 file of the same name)
' from startfolder and all subfolders
Function AllFilesbyName(startFolder As String, filePattern As String, _
Optional subFolders As Boolean = True) As Object
Dim fso, fldr, f, subFldr
Dim dictFiles As Object, colSub As New Collection
Set fso = CreateObject("scripting.filesystemobject")
Set dictFiles = CreateObject("scripting.dictionary")
dictFiles.comparemode = 1 'TextCompare: case-insensitive
colSub.Add startFolder
Do While colSub.Count > 0
Set fldr = fso.getfolder(colSub(1))
colSub.Remove 1
For Each f In fldr.Files
If UCase(f.Name) Like UCase(filePattern) Then
'EDIT: fixed the line below
dictFiles(f.Name) = fso.buildpath(fldr.Path, f.Name)
End If
Next f
If subFolders Then
For Each subFldr In fldr.subFolders
colSub.Add subFldr.Path
Next subFldr
End If
Loop
Set AllFilesbyName = dictFiles
End Function
I have to count the number of mails received within certain criterion for weekly reporting. The mails are in various folders and subfolders of Outlook.
Dim objOutlook As Object, objnSpace As Object, objFolder As Outlook.MAPIFolder
Dim EmailCount As Integer
Sub HowManyDatedEmails()
Set objOutlook = CreateObject("Outlook.Application")
Set objnSpace = objOutlook.GetNamespace("MAPI")
On Error Resume Next
Set objFolder = objnSpace.GetDefaultFolder(olFolderInbox)
If Err.Number <> 0 Then
Err.Clear
MsgBox "No such folder."
Exit Sub
End If
Dim iCount As Integer, DateCount1 As Integer
Dim myDate1 As Date
Dim myDate2 As Date
Dim DateCount2 As Integer
EmailCount = objFolder.Items.Count
DateCount1 = 0
DateCount2 = 0
myDate1 = Sheets("Sheet1").Range("A1").Value
myDate2 = Sheets("Sheet1").Range("B1").Value
For iCount = 1 To EmailCount
With objFolder.Items(iCount)
If DateSerial(Year(.ReceivedTime), Month(.ReceivedTime), Day(.ReceivedTime)) >= myDate1 And _
DateSerial(Year(.ReceivedTime), Month(.ReceivedTime), Day(.ReceivedTime)) <= myDate2 And _
.SenderEmailAddress Like "*kailash*" Then
DateCount1 = DateCount1 + 1
End If
If DateSerial(Year(.ReceivedTime), Month(.ReceivedTime), Day(.ReceivedTime)) >= myDate1 And _
DateSerial(Year(.ReceivedTime), Month(.ReceivedTime), Day(.ReceivedTime)) <= myDate2 And _
.SenderEmailAddress Like "*soumendra*" Then
DateCount2 = DateCount2 + 1
End If
End With
Next iCount
Set objFolder = Nothing
Set objnSpace = Nothing
Set objOutlook = Nothing
Sheets("Sheet1").Range("B2").Value = DateCount1
Sheets("Sheet1").Range("B3").Value = DateCount2
End Sub
I want Excel VBA code such that the sheet list shows the count figure against the criterion number.
I am able to do it for one folder but I want to achieve it for all folders and subfolders recursively in Inbox.
As I said in my comment, this is an Outlook macro. I can show you how to convert it to an Excel macro if necessary. If you need more help, you must expand your question.
Sub ListStoresAndAllFolders()
' Displays the name of every accessible store
' Under each store, displays an indented list of all its folders
' Technique for locating desktop from answer by Kyle:
' http://stackoverflow.com/a/17551579/973283
' Needs reference to Microsoft Scripting Runtime if "TextStream"
' and "FileSystemObject" are to be recognised
Dim FileOut As TextStream
Dim FldrCrnt As Folder
Dim Fso As FileSystemObject
Dim InxFldrChild As Long
Dim InxStoreCrnt As Long
Dim Path As String
Dim StoreCrnt As Folder
Path = CreateObject("WScript.Shell").specialfolders("Desktop")
Set Fso = CreateObject("Scripting.FileSystemObject")
Set FileOut = Fso.CreateTextFile(Path & "\ListStoresAndAllFolders.txt", True)
With Application.Session
For InxStoreCrnt = 1 To .Folders.Count
Set StoreCrnt = .Folders(InxStoreCrnt)
With StoreCrnt
FileOut.WriteLine .Name
For InxFldrChild = .Folders.Count To 1 Step -1
Set FldrCrnt = .Folders(InxFldrChild)
Call ListAllFolders(FldrCrnt, 1, FileOut)
Next
End With
Next
End With
FileOut.Close
End Sub
Sub ListAllFolders(ByRef Fldr As Folder, ByVal Level As Long, ByRef FileOut As TextStream)
' This routine:
' 1. Output name of Fldr
' 2. Calls itself for each child of Fldr
' It is designed to be called by ListStoresAndAllFolders()
Dim InxFldrChild As Long
With Fldr
FileOut.WriteLine Space(Level * 2) & .Name
For InxFldrChild = .Folders.Count To 1 Step -1
Call ListAllFolders(.Folders(InxFldrChild), Level + 1, FileOut)
Next
End With
End Sub
Trying to find MS Excel/VBA code to move all subfolders with lastdatemodified < date -30 to a different folder.
Like this (but obviously not this)
foldertomove = subfolder
folder = main
newfolder = archive
for each subfolder in main
if subfolder.datelastmodified < date - 30 then
move subfolder to archive
end if
next
Any help is greatly appreciated! Thanks!
Objective of this program is to Copy Folders, Sub-Folders and Folders
within Folders along with files contained in them. It could be any type of the file PDF, Text, Word, Excel etc.
This program will only copy Files which are 30 days older from
Current Time. User can adjust this date or between two dates as per
his requirements.
When program is run File Picker Dialog will open and allow user to
chose the folder to be archived.
It is very important that an Empty Directory Structure with same
folder structure as parent folder to be archived has is created.
Presently VBA code for this step has not been incorporated in this
program. Simplest way is to copy paste folder and then delete files
in various folders and sub-folders manually. It is one time exercise
so long as parent directory structure remains the same. Any changes
in the parent directory structure are also to be incorporated in the
Archive folder also.
Program will also output Directory and File Paths on a separate
workbook of the parent directory being archived. If it is not
required then relevant portions of the program can be commented out.
Snapshot of output is placed below.
Further improvements in this program shall be endeavoured based on feedback and help of experts.
Code is placed below.
Sub CopyFolders_Recursively()
Dim strFolder As String
Dim objFSO As Object
Dim objFolder As Object
Dim myResults As Variant
Dim lCount As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Get the directory from the user
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then Exit Sub
'user cancelled
strFolder = .SelectedItems(1)
End With
Set objFolder = objFSO.GetFolder(strFolder)
'the variable dimension has to be the second one
ReDim myResults(0 To 5, 0 To 0)
' place make some headers in the array
myResults(0, 0) = "Filename"
myResults(1, 0) = "Size"
myResults(2, 0) = "Created"
myResults(3, 0) = "Modified"
myResults(4, 0) = "Accessed"
myResults(5, 0) = "Full path"
'Send the folder to the recursive function
FillFileList objFolder, myResults, lCount
' Dump these to a worksheet
fcnDumpToWorksheet myResults
'tidy up
Set objFSO = Nothing
End Sub
Private Sub FillFileList(objFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)
Dim i As Integer
Dim objFile As Object
Dim fsoSubFolder As Object
Dim fsoSubFolders As Object
Dim ToPath As String
Dim lpath As String
ToPath = "C:\Archive\"
Dim Fdtdiff As Integer
'load the array with all the files
For Each objFile In objFolder.Files
lCount = lCount + 1
ReDim Preserve myResults(0 To 5, 0 To lCount)
myResults(0, lCount) = objFile.Name
myResults(1, lCount) = objFile.Size
myResults(2, lCount) = objFile.DateCreated
myResults(3, lCount) = objFile.DateLastModified
myResults(4, lCount) = objFile.DateLastAccessed
myResults(5, lCount) = objFile.Path
Fdtdiff = DateValue(Now) - DateValue(myResults(3, lCount))
If Fdtdiff > 30 Then
lpath = Replace(objFile.Path, "my_dir", "Archive")
objFile.Copy lpath
End If
Next objFile
'recursively call this function with any subfolders
Set fsoSubFolders = objFolder.SubFolders
For Each fsoSubFolder In fsoSubFolders
FillFileList fsoSubFolder, myResults, lCount
Next fsoSubFolder
End Sub
Private Sub fcnDumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
Dim iSheetsInNew As Integer
Dim sh As Worksheet, wb As Workbook
Dim myColumnHeaders() As String
Dim l As Long, NoOfRows As Long
If mySh Is Nothing Then
'make a workbook if we didn't get a worksheet
iSheetsInNew = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1
Set wb = Application.Workbooks.Add
Application.SheetsInNewWorkbook = iSheetsInNew
Set sh = wb.Sheets(1)
Else
Set mySh = sh
End If
'since we switched the array dimensions, have to transpose
With sh
Range(.Cells(1, 1), .Cells(UBound(varData, 2) + 1, UBound(varData, 1) + 1)) = _
Application.WorksheetFunction.Transpose(varData)
.UsedRange.Columns.AutoFit
End With
Set sh = Nothing
Set wb = Nothing
End Sub
Private Sub CopyFolders_Recursively()
Dim strFolder As String
Dim objFSO As Object
Dim objFolder As Object
Dim myResults As Variant
Dim lCount As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Get the directory from the user
'With Application.FileDialog(msoFileDialogFolderPicker)
'.Show
'If .SelectedItems.Count = 0 Then Exit Sub
'user cancelled
'strFolder = .SelectedItems(1)
'End With
strFolder = "D:\testing\" '<<change
Set objFolder = objFSO.GetFolder(strFolder)
'the variable dimension has to be the second one
ReDim myResults(0 To 5, 0 To 0)
' place make some headers in the array
myResults(0, 0) = "Filename"
myResults(1, 0) = "Size"
myResults(2, 0) = "Created"
myResults(3, 0) = "Modified"
myResults(4, 0) = "Accessed"
myResults(5, 0) = "Full path"
'Send the folder to the recursive function
FillFileList objFolder, myResults, lCount
' Dump these to a worksheet
fcnDumpToWorksheet myResults
CleanUpList
If Range("A2").Value = "" Then GoTo tidyup
AddFolders
Move_Folders
tidyup:
Cells.Delete
Range("A1").Select
'tidy up
Set objFSO = Nothing
End Sub
Private Sub FillFileList(objFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)
Dim i As Integer
Dim objFile As Object
Dim fsoSubFolder As Object
Dim fsoSubFolders As Object
Dim lpath As String
Dim Fdtdiff As Integer
'load the array with all the files
For Each objFile In objFolder.Files
If InStr(objFile.Path, "~Archive") = 0 Then 'don't get files from the archive folder (assumes the archive folder is a subfolder of the folder from which you're moving the other subfolders
lCount = lCount + 1
ReDim Preserve myResults(0 To 5, 0 To lCount)
myResults(0, lCount) = objFile.Name
myResults(1, lCount) = objFile.Size
myResults(2, lCount) = objFile.DateCreated
myResults(3, lCount) = objFile.DateLastModified
myResults(4, lCount) = objFile.DateLastAccessed
myResults(5, lCount) = objFile.Path
'Fdtdiff = DateValue(Now) - DateValue(myResults(3, lCount))
'If Fdtdiff > 30 Then
'lpath = Replace(objFile.Path, "my_dir", "~Archive")
'objFile.Copy lpath
'End If
End If
Next objFile
'recursively call this function with any subfolders
Set fsoSubFolders = objFolder.SubFolders
For Each fsoSubFolder In fsoSubFolders
FillFileList fsoSubFolder, myResults, lCount
Next fsoSubFolder
End Sub
Private Sub fcnDumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
'since we switched the array dimensions, have to transpose
With ThisWorkbook.Sheets(1) '<<change
Cells.ClearContents
Range(.Cells(1, 1), .Cells(UBound(varData, 2) + 1, UBound(varData, 1) + 1)) = _
Application.WorksheetFunction.Transpose(varData)
.UsedRange.Columns.AutoFit
End With
End Sub
Private Sub CleanUpList()
'sort most recent files to the top so when we remove dupes we'll be left with the most recent one
ThisWorkbook.Worksheets("Archive").Sort.SortFields.Clear '<<change sheet name
ThisWorkbook.Worksheets("Archive").Sort.SortFields.Add Key:=Range("D2:D65536") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ThisWorkbook.Worksheets("Archive").Sort
.SetRange Range("A1:F65536")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'remove parent folder from path we'll check later
Columns("F:F").Replace What:="D:\testing\", Replacement:="", LookAt:=xlPart, MatchCase:=False '<< Change
'remove file name, leaving just the folder we want to move
Columns("F:F").Replace What:="\*", Replacement:="", LookAt:=xlPart, MatchCase:=False
'we just need one!
ThisWorkbook.Sheets(1).Range("$A$1:$AZ$65536").RemoveDuplicates Columns:=6, Header:=xlYes '<< remove dupes of folders to move
Set Rng = Range("D1:D100") '<< change if you know it will be less or more than 100
For Each cell In Rng
If cell.Value <> "" Then
If cell.Value > Date - 30 Then '<<only keep it if more than 30 days (or whatever you want)
cell.Value = ""
End If
End If
Next
On Error Resume Next
Columns("D:D").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error GoTo 0
End Sub
Private Sub AddFolders() 'we'll archive by year within the archive subfolder
Set Rng = Range("D2:D100") '<< change if you know it will be less or more than 100
For Each x In Rng
If x.Value <> "" Then
On Error Resume Next
MkDir "D:\testing\~Archive\" & Format(x.Value - 30, "yyyy") '<< Change
On Error GoTo 0
End If
Next x
End Sub
Private Sub Move_Folders()
'This example move the folder from FromPath to ToPath
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Set Rng = Range("F2:F100") '<< change if you know it will be less or more than 100
For Each x In Rng
If x.Value <> "" Then
FromPath = "D:\testing\" & x.Value '<< Change
ToPath = "D:\testing\~Archive\" & Format(x.Offset(0, -2).Value - 30, "yyyy") & "\" & x.Value '<< Change
'Note: It is not possible to use a folder that exist in ToPath
'We created subfolders by year earlier so we can archive by year now
Set FSO = CreateObject("scripting.filesystemobject")
FSO.MoveFolder Source:=FromPath, Destination:=ToPath
End If
Next x
End Sub
Figured out a more direct way to get the subfolders needed to be archived:
Private Sub Archive_Hotel_Confs()
Sheets("Archiving").Select
Cells.ClearContents
Dim strStartPath As String
strStartPath = "W:testing\" 'ENTER YOUR START FOLDER HERE
ListHCFolder strStartPath
CleanUpList
If Range("A1").Value = "" Then GoTo tidyup
AddHCFolders
MoveHC_Folders
'tidy up
tidyup:
Cells.Delete
Range("A1").Select
Sheets("Last Run").Select
End Sub
Private Sub ListHCFolder(sFolderPath As String)
Dim FS As New FileSystemObject
Dim FSfolder As Folder
Dim subfolder As Folder
Dim i As Integer
Set FSfolder = FS.GetFolder(sFolderPath)
For Each subfolder In FSfolder.SubFolders
If InStr(subfolder.Name, "~Archive") = 0 Then
DoEvents
i = i + 1
'added this line
Cells(i, 1) = subfolder
Cells(i, 2) = subfolder.DateLastModified
'commented out this one
'Debug.Print subfolder
End If
Next subfolder
Set FSfolder = Nothing
End Sub
Private Sub CleanUpList()
Dim x As Variant
'remove parent folder from path we'll check later
Columns("A:A").Replace What:="W:testing\", Replacement:="", LookAt:=xlPart, MatchCase:=False '<< Change
Set Rng = Range(Range("B1"), Range("B" & Rows.Count).End(xlUp))
For Each x In Rng
If x.Value <> "" Then
If x.Value > Date - 30 Then '<<only keep it if more than 30 days (or whatever you want)
x.Value = ""
End If
End If
Next x
On Error Resume Next
Columns("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error GoTo 0
End Sub
Private Sub AddHCFolders() 'we'll archive by year within the archive subfolder
Dim x As Variant
Set Rng = Range(Range("B1"), Range("B" & Rows.Count).End(xlUp))
For Each x In Rng
If x.Value <> "" Then
On Error Resume Next
MkDir "W:testing\~Archive\" & Format(x.Value - 30, "yyyy") '<< Change
On Error GoTo 0
End If
Next x
End Sub
Private Sub MoveHC_Folders()
'This example move the folder from FromPath to ToPath
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim x As Variant
Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
For Each x In Rng
If x.Value <> "" Then
FromPath = "W:testing\" & x.Value '<< Change
ToPath = "W:testing\~Archive\" & Format(x.Offset(0, 1).Value - 30, "yyyy") & "\" & x.Value '<< Change
'Note: It is not possible to use a folder that exist in ToPath
'We created subfolders by year earlier so we can archive by year now
Set FSO = CreateObject("scripting.filesystemobject")
FSO.MoveFolder Source:=FromPath, Destination:=ToPath
End If
Next x
End Sub
Hello please help me yo solve this.
I have multiple workbook and I want to copy a specific cell in each workbook into another workbook orderly.
Great thanks
Sophannaa
Copy this whole code to the list of your choice(to visual basic of course).
Run this by running begin().
Change values in part"HERE COMES YOUR PART!!!"
Sub begin()
ThisWorkbook.Save
DoEvents
Const ROW_FIRST As Integer = 5
Dim intResult As Integer
Dim strPath As String
Dim objFSO As Object
Dim intCountRows As Integer
Dim sourceWB As Workbook
Dim targetWB As Workbook
Set targetWB = ThisWorkbook
Dim xrow As Integer
xrow = 5
Application.FileDialog(msoFileDialogFolderPicker).Title = "Please select File to load"
Application.FileDialog(msoFileDialogFolderPicker).ButtonName = "Choose a file"
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
For Each Item In Application.FileDialog(msoFileDialogFolderPicker).SelectedItems
If intResult <> 0 Then
Application.ScreenUpdating = False
Range("A:A").ClearContents
Range("B:B").ClearContents
Range("C:C").ClearContents
Cells(4, 1).Value = "NAME"
Cells(4, 2).Value = "PATH"
Cells(4, 3).Value = "TAIL"
strPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
Set objFSO = CreateObject("Scripting.FileSystemObject")
intCountRows = GetAllFiles(strPath, ROW_FIRST, objFSO)
Call GetAllFolders(strPath, objFSO, intCountRows)
Application.ScreenUpdating = True
End If
Next Item
Cells(1, 1).Value = Application.WorksheetFunction.CountA(Range("B:B")) - 1
'HERE COMES YOUR PART!!!
Dim nextrow As Integer
nextrow = 2 'choose starting row where to copy the results
Do
strFile = Cells(xrow, 2).Value
Set sourceWB = Workbooks.Open(strFile)
targetWB.Sheets("desired sheet to copy to").Cells(nextrow, 1) = sourceWB.Sheets("desired sheet to copy from").Cells(2, 1)
'instead of cells(2,1) up here ^^ and here^^ choose what cells you want to copy from, edit only numbers
sourceWB.Save
sourceWB.Close
xrow = xrow + 1
nextrow = nextrow + 1
Loop Until ThisWorkbook.Sheets(1).Cells(xrow, 2).Value = ""
End Sub
Private Function GetAllFiles(ByVal strPath As String, ByVal intRow As Integer, ByRef objFSO As Object) As Integer
DoEvents
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
inte = InStr(1, objFile.Name, "prázdný")
Cells(i + ROW_FIRST - 1, 1) = objFile.Name
Cells(i + ROW_FIRST - 1, 2) = objFile.Path
Cells(i + ROW_FIRST - 1, 3) = Right(objFile.Name, Len(objFile.Name) - InStrRev(objFile.Name, "."))
i = i + 1
Next objFile
GetAllFiles = i + ROW_FIRST - 1
End Function
Private Sub GetAllFolders(ByVal strFolder As String, ByRef objFSO As Object, ByRef intRow As Integer)
DoEvents
Dim objFolder As Object
Dim objSubFolder As Object
Static veSpravneSlozce As Boolean
Set objFolder = objFSO.GetFolder(strFolder)
For Each objSubFolder In objFolder.subfolders
intRow = GetAllFiles(objSubFolder.Path, intRow, objFSO)
Call GetAllFolders(objSubFolder.Path, objFSO, intRow)
Next objSubFolder
End Sub
Since it is really useless to copy all values to one cell a added nextrow to shift cells and write down values one after another