I am receiving a "Object reference not set to an instance of an object." Error when trying to populate the fileDetails array. I am new to vb.net and I am lost.
Public Sub FindAllOrphanFiles(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
' Process the list of files found in the directory.
Dim files As String
Dim iCount As Integer = 0
Dim fileDetails As String(,)
For Each files In fileEntries
Dim fileIcon As String
Dim thisFile As New IO.FileInfo(files)
Dim fileName As String = thisFile.Name
Dim fileSize As String = thisFile.Length
Dim fileDateModified As String = thisFile.LastWriteTime
Dim fileExtension As String = Path.GetExtension(fileName)
Dim fileShortPath As String = Replace(Replace(files, uploadFolderPath, ""), fileName, "")
Dim fileFullPath As String = files
If fileExtension = ".pdf" Then
fileIcon = "acrobat"
Else
fileIcon = "paint"
End If
' Write to Array
fileDetails(iCount, 0) = fileIcon
fileDetails(iCount, 1) = fileName
fileDetails(iCount, 2) = fileShortPath
fileDetails(iCount, 3) = fileDateModified
fileDetails(iCount, 4) = fileSize
fileDetails(iCount, 5) = fileFullPath
iCount += 1
Next files
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
' Recurse into subdirectories of this directory.
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
FindAllOrphanFiles(subdirectory)
Next subdirectory
End Sub 'FindAllOrphanFiles
Any help would be greatly appreciated.
Your array is not initialized. If you know the size at some point before your loop, you should initialize it using REDIM:
Dim fileDetails As String(,)
redim fileDetails(fileEntries.Count -1,5)
For Each files In fileEntries
....
If you don't know it ahead of time, use Redim Preserve inside you loop:
Dim fileDetails As String(,)
Dim I as int32 = -1
For Each files In fileEntries
I += 1
redim preserve fileDetails(i,5)
....
Related
how to move existing file to another folder using asp, but i will send file series "scn_1" only
FROM -- > d:\image\scn_1_1.jpg , d:]image\scn_1_2.jpg
TO --> d:\image2\backup\scn_1_1.jpg, scn_1_2.jpg
in asp or vb
this is my sample code
Dim fs
fs = Server.CreateObject("Scripting.FileSystemObject")
Dim scanpath = Request.QueryString("spath")
Dim rkpath = Request.QueryString("rkpath")
Dim series = Request.QueryString("series")
fs.MoveFile("D:\Ethiraj\ScanDcocument\scanimage\test.txt", "D:\Ethiraj\ScanDcocument\Rk_Images\test.txt")
fs = Nothing
Dim fs fs = Server.CreateObject("Scripting.FileSystemObject") Dim scanpath = Request.QueryString("virtu_dir") Dim rkpath = Request.QueryString("RK_path") Dim series = Request.QueryString("series") Dim fileToFind = series & "*.jpg" Dim dirs As String() = IO.Directory.GetFiles(scanpath, fileToFind) Dim dir As String For Each dir In dirs If dir.Contains(series) Then Dim filename = System.IO.Path.GetFileName(dir) fs.CopyFile(dir, rkpath + "\" + filename) fs = Nothing End If Next
I have an issue where only the last page of my pdf is stored.
The pdf should be multiple pages long, and this works fine if I just send the pdf to the browser using Response and the mms memory stream, however I need to add it as a pdf to an email and therefore are writing mms to bytes to create a new memorystream when I create my email attachment. This is to get around the closed stream error.
This is my code
Public Shared Function SendPrePackLabels(ByVal bf_id As String, mail As String) As Boolean
Dim pars(0) As SqlParameter
pars(0) = New SqlParameter("#bf_id", SqlDbType.VarChar) With {.Value = bf_id}
Dim p As String
Dim reader As PdfReader
Dim mms As New MemoryStream
Dim rt() As Byte
Dim i As Integer = 0
Using dc As Document = New Document
Using sc As PdfSmartCopy = New PdfSmartCopy(dc, System.Web.HttpContext.Current.Response.OutputStream)
dc.Open()
With SqlHelper.ExecuteDataset(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spPrepack_Labels", pars).Tables(0)
For Each dr As DataRow In .Rows
Dim pdfr As New PdfReader("http://192.168.0.221/template.pdf")
Using ms As New MemoryStream
Using pdfs As New PdfStamper(pdfr, ms)
Dim fields As AcroFields = pdfs.AcroFields
fields.GenerateAppearances = True
fields.SetField("pono", dr.Item("po_no").ToString)
fields.SetField("ref", dr.Item("alt_code").ToString)
fields.SetField("colour", dr.Item("colour").ToString)
fields.SetField("code", dr.Item("sizerun_hdr_id").ToString)
For k As Integer = 1 To dr.Table.Columns.Count - 6
Dim j As Integer = k + 5
fields.SetField("s" & k, dr.Table.Columns(j).ColumnName.ToString)
If dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString = "" Then
p = "0"
Else
p = dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString
End If
fields.SetField("p" & k, p)
Next
fields.SetField("pack", dr.Item("sizerun_hdr_id").ToString)
Dim bcfont As BaseFont = BaseFont.CreateFont("http://192.168.0.221/ean.ttf", BaseFont.CP1252, BaseFont.EMBEDDED)
fields.SetFieldProperty("barcode", "textfont", bcfont, Nothing)
fields.SetFieldProperty("barcode", "textsize", 60.0F, Nothing)
Dim mBarcode As String = "219" & dr.Item("sizerun_hdr_id").ToString
Dim cLength As Integer = mBarcode.Length
Dim zerostoadd As Integer = 12 - cLength
Dim digit12barcode As String = mBarcode.PadRight(12, CChar("0"))
Dim FinalBarcode As String = returnCheckDigitedBarcode(digit12barcode)
fields.SetField("barcode", FinalBarcode)
Dim par(1) As SqlParameter
par(0) = New SqlParameter("#sizerun_hdr_id", SqlDbType.VarChar) With {.Value = dr.Item("sizerun_hdr_id").ToString}
par(1) = New SqlParameter("#ean13", SqlDbType.VarChar) With {.Value = FinalBarcode}
SqlHelper.ExecuteScalar(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spSizeRunEAN13", par)
pdfs.FormFlattening = True
ms.Flush()
End Using
reader = New PdfReader(ms.ToArray)
sc.AddPage(sc.GetImportedPage(reader, 1))
mms = ms
End Using
Next
End With
End Using
End Using
Dim bt() As Byte = mms.ToArray
Try
If mail.Length > 0 Then
Dim eMsg As New MailMessage()
eMsg.From = New MailAddress("myemail#mydomain.co.uk")
eMsg.To.Add(New MailAddress(mail))
Dim title As String = "<h3>Here are the Prepack Labels.</h3>"
eMsg.Subject = "Prepack Labels"
eMsg.Body = "<html>" & title & "</html>"
eMsg.IsBodyHtml = True
Dim att As Attachment = New Attachment(New MemoryStream(bt), "Prepack Labels.pdf", "application/pdf")
eMsg.Attachments.Add(att)
Dim SMTP1 As New SmtpClient
SMTP1.Host = "EX"
SMTP1.Send(eMsg)
att.Dispose()
End If
Return True
Catch ex As Exception
Return False
End Try
End Function
I'm not sure of your exact problem but I'm pretty sure your life would be easier if you broke you giant function into smaller more specific functions that do only one thing. Also, I really recommend never writing to the raw ASP.Net stream until after you've created a PDF. Instead, always write to a MemoryStream, grab the bytes and do something with them.
The code below break it into four functions. CreatePdf() loops through the database and calls CreateSinglePdf() for each row in the table, merging them with your PdfSmartCopy. SendEmail() is blissfully unaware of iTextSharp completely and just receives a raw array of bytes that is assumed to be a PDF. This is all kicked off by SendPrePackLabels() which is where you'd probably want to also Response.BinaryWrite() your bytes.
Public Shared Function SendPrePackLabels(ByVal bf_id As String, mail As String) As Boolean
Dim bt = CreatePdf(bf_id)
Return SendEmail(bt, mail)
End Function
Public Shared Function CreateSinglePdf(dr As DataRow) As Byte()
Using ms As New MemoryStream
Using pdfr As New PdfReader("http://192.168.0.221/template.pdf")
Using pdfs As New PdfStamper(pdfr, ms)
Dim fields As AcroFields = pdfs.AcroFields
fields.GenerateAppearances = True
fields.SetField("pono", dr.Item("po_no").ToString)
fields.SetField("ref", dr.Item("alt_code").ToString)
fields.SetField("colour", dr.Item("colour").ToString)
fields.SetField("code", dr.Item("sizerun_hdr_id").ToString)
Dim p As String
For k As Integer = 1 To dr.Table.Columns.Count - 6
Dim j As Integer = k + 5
fields.SetField("s" & k, dr.Table.Columns(j).ColumnName.ToString)
If dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString = "" Then
p = "0"
Else
p = dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString
End If
fields.SetField("p" & k, p)
Next
fields.SetField("pack", dr.Item("sizerun_hdr_id").ToString)
Dim bcfont As BaseFont = BaseFont.CreateFont("http://192.168.0.221/ean.ttf", BaseFont.CP1252, BaseFont.EMBEDDED)
fields.SetFieldProperty("barcode", "textfont", bcfont, Nothing)
fields.SetFieldProperty("barcode", "textsize", 60.0F, Nothing)
Dim mBarcode As String = "219" & dr.Item("sizerun_hdr_id").ToString
Dim cLength As Integer = mBarcode.Length
Dim zerostoadd As Integer = 12 - cLength
Dim digit12barcode As String = mBarcode.PadRight(12, CChar("0"))
Dim FinalBarcode As String = returnCheckDigitedBarcode(digit12barcode)
fields.SetField("barcode", FinalBarcode)
Dim par(1) As SqlParameter
par(0) = New SqlParameter("#sizerun_hdr_id", SqlDbType.VarChar) With {.Value = dr.Item("sizerun_hdr_id").ToString}
par(1) = New SqlParameter("#ean13", SqlDbType.VarChar) With {.Value = FinalBarcode}
SqlHelper.ExecuteScalar(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spSizeRunEAN13", par)
pdfs.FormFlattening = True
End Using
End Using
Return ms.ToArray()
End Using
End Function
Public Shared Function CreatePdf(ByVal bf_id As String) As Byte()
Dim pars(0) As SqlParameter
pars(0) = New SqlParameter("#bf_id", SqlDbType.VarChar) With {.Value = bf_id}
Using ms As New System.IO.MemoryStream
Using dc As Document = New Document
Using sc As PdfSmartCopy = New PdfSmartCopy(dc, ms)
dc.Open()
With SqlHelper.ExecuteDataset(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spPrepack_Labels", pars).Tables(0)
For Each dr As DataRow In .Rows
Dim pageBytes = CreateSinglePdf(dr)
Using reader = New PdfReader(pageBytes)
sc.AddPage(sc.GetImportedPage(reader, 1))
End Using
Next
End With
End Using
End Using
Return ms.ToArray()
End Using
End Function
Public Shared Function SendEmail(bt As Byte(), mail As String) As Boolean
Try
If mail.Length > 0 Then
Dim eMsg As New MailMessage()
eMsg.From = New MailAddress("myemail#mydomain.co.uk")
eMsg.To.Add(New MailAddress(mail))
Dim title As String = "<h3>Here are the Prepack Labels.</h3>"
eMsg.Subject = "Prepack Labels"
eMsg.Body = "<html>" & title & "</html>"
eMsg.IsBodyHtml = True
Dim att As Attachment = New Attachment(New MemoryStream(bt), "Prepack Labels.pdf", "application/pdf")
eMsg.Attachments.Add(att)
Dim SMTP1 As New SmtpClient
SMTP1.Host = "EX"
SMTP1.Send(eMsg)
att.Dispose()
End If
Return True
Catch ex As Exception
Return False
End Try
End Function
i am doing a method that able to return me what is the different between data before and data after
Dim dataBefore As String = "Name:Alice,Age:30,Sex:Male"
Dim dataAfter As String = "Name:Alice,Age:20,Sex:Female"
mtdCompare2String(dataBefore,dataAfter)
Public Shared Function mtdCompare2String(ByVal sBefore As String, ByVal sAfter As String) As String
//what i try to do before, supposing my loop should start over here but i failed,
//so i just removed the loop, i need someone to correct me =(
Dim intBefore As Integer = sBefore.IndexOf(",")
Dim intAfter As Integer = sAfter.IndexOf(",")
Dim sBefore As String = sBefore.SubString(0,intBefore)
Dim sAfter As String = sAfter.SubString(sAfter.IndexOf(":"),intAfter)
Dim sb As StringBuilder
sb.append(sBefore,sAfter)
return sb.toString
End Function
Expected Result
Age:30>20,Sex:Male>Female
Something like this should work:
Public Shared Function mtdCompare2String(ByVal sBefore As String, ByVal sAfter As String) As String
'what i try to do before, supposing my loop should start over here but i failed,
'so i just removed the loop, i need someone to correct me =(
Dim Before() As String = sBefore.Split(",")
Dim After() As String = sAfter.Split(",")
Dim ReturnString As String = ""
For I = 0 To Before.Length - 1
Dim TempBefore As String = Before(I).Split(":")(1)
Dim TempAfter As String = After(I).Split(":")(1)
If TempBefore <> TempAfter Then
ReturnString += Before(I).Split(":")(0) + ":" + TempBefore + ">" + TempAfter + ","
End If
Next
Return ReturnString.Substring(0, ReturnString.Length - 1)
End Function
Here is my code that uploads a file to a folder...but I need to upload a file to a folder which might not exist yet. How can i create a folder before uploading the file or is there a parameter in asp that creates a folder before copying the file there if it doesn't exit?..i need to create folder based on the user input...
<%
Class FileUploader
Public Files
Private mcolFormElem
Private Sub Class_Initialize()
Set Files = Server.CreateObject("Scripting.Dictionary")
Set mcolFormElem = Server.CreateObject("Scripting.Dictionary")
End Sub
Private Sub Class_Terminate()
If IsObject(Files) Then
Files.RemoveAll()
Set Files = Nothing
End If
If IsObject(mcolFormElem) Then
mcolFormElem.RemoveAll()
Set mcolFormElem = Nothing
End If
End Sub
Public Property Get Form(sIndex)
Form = ""
If mcolFormElem.Exists(LCase(sIndex)) Then Form = mcolFormElem.Item(LCase(sIndex))
End Property
Public Default Sub Upload()
Dim biData, sInputName
Dim nPosBegin, nPosEnd, nPos, vDataBounds, nDataBoundPos
Dim nPosFile, nPosBound
biData = Request.BinaryRead(Request.TotalBytes)
nPosBegin = 1
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))
If (nPosEnd-nPosBegin) <= 0 Then Exit Sub
vDataBounds = MidB(biData, nPosBegin, nPosEnd-nPosBegin)
nDataBoundPos = InstrB(1, biData, vDataBounds)
Do Until nDataBoundPos = InstrB(biData, vDataBounds & CByteString("--"))
nPos = InstrB(nDataBoundPos, biData, CByteString("Content-Disposition"))
nPos = InstrB(nPos, biData, CByteString("name="))
nPosBegin = nPos + 6
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(34)))
sInputName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
nPosFile = InstrB(nDataBoundPos, biData, CByteString("filename="))
nPosBound = InstrB(nPosEnd, biData, vDataBounds)
If nPosFile <> 0 And nPosFile < nPosBound Then
Dim oUploadFile, sFileName
Set oUploadFile = New UploadedFile
nPosBegin = nPosFile + 10
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(34)))
sFileName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
oUploadFile.FileName = Right(sFileName, Len(sFileName)-InStrRev(sFileName, "\"))
nPos = InstrB(nPosEnd, biData, CByteString("Content-Type:"))
nPosBegin = nPos + 14
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))
oUploadFile.ContentType = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
nPosBegin = nPosEnd+4
nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2
oUploadFile.FileData = MidB(biData, nPosBegin, nPosEnd-nPosBegin)
If oUploadFile.FileSize > 0 Then Files.Add LCase(sInputName), oUploadFile
Else
nPos = InstrB(nPos, biData, CByteString(Chr(13)))
nPosBegin = nPos + 4
nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2
If Not mcolFormElem.Exists(LCase(sInputName)) Then mcolFormElem.Add LCase(sInputName), CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
End If
nDataBoundPos = InstrB(nDataBoundPos + LenB(vDataBounds), biData, vDataBounds)
Loop
End Sub
'String to byte string conversion
Private Function CByteString(sString)
Dim nIndex
For nIndex = 1 to Len(sString)
CByteString = CByteString & ChrB(AscB(Mid(sString,nIndex,1)))
Next
End Function
'Byte string to string conversion
Private Function CWideString(bsString)
Dim nIndex
CWideString =""
For nIndex = 1 to LenB(bsString)
CWideString = CWideString & Chr(AscB(MidB(bsString,nIndex,1)))
Next
End Function
End Class
Class UploadedFile
Public ContentType
Public FileName
Public FileData
Public Property Get FileSize()
FileSize = LenB(FileData)
End Property
Public Sub SaveToDisk(sPath)
Dim oFS, oFile
Dim nIndex
If sPath = "" Or FileName = "" Then Exit Sub
If Mid(sPath, Len(sPath)) <> "\" Then sPath = sPath & "\"
Set oFS = Server.CreateObject("Scripting.FileSystemObject")
If Not oFS.FolderExists(sPath) Then Exit Sub
Set oFile = oFS.CreateTextFile(sPath & FileName, True)
For nIndex = 1 to LenB(FileData)
oFile.Write Chr(AscB(MidB(FileData,nIndex,1)))
Next
oFile.Close
End Sub
Public Sub SaveToDatabase(ByRef oField)
If LenB(FileData) = 0 Then Exit Sub
If IsObject(oField) Then
oField.AppendChunk FileData
End If
End Sub
End Class
%>
can anybody help me?
i need to upload the set of documents corresponding to that proforma number...so i need to create a folder in the name of proforma number which is entered by the user...
just use the filesystemobject to create a directory like so:
dim fso : set fso = server.createobject("scripting.filesystemobject")
dim absolutePath : absolutePath = "d:\path\to\new\directory"
if not fso.FolderExists(absolutePath) then
fso.createFolder( absolutePath )
end if
set fso = nothing
check the api doc for fso
to use that "proforma" number just get it from request.form("name_for_proforma_field")...
as you are using the upload class you have to use
fileUploader.Form("name_for_proforma_field")
instead of
request.form
because after using request.binaryread you do not have access to the request.forms collection...
brief example (not tested):
dim upl : set upl = new FileUploader()
upl.upload()
' from now on you have to use upl.Form() instad of request.form
dim folderName : folderName = upl.Form("name_for_proforma_field")
dim fso : set fso = server.createobject("scripting.filesystemobject")
dim absolutePath : absolutePath = "d:\path\to\new\directory\" & folderName
if not fso.FolderExists(absolutePath) then
fso.createFolder( absolutePath )
end if
set fso = nothing
for further information about the fileupload class have a look here
Im having trouble converting a working solution that takes a directory folder as an input and outputs the filenames and other file attributes of files container in the folder into an excel spreadsheet to a recursive solution that also outputs the files contained in subfolders. I would greatly appreciate any help!
Sub GetFileList()
Dim strFolder As String
Dim varFileList As Variant
Dim FSO As Object, myFile As Object
Dim myResults As Variant
Dim l As Long
' 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
' Get a list of all the files in this directory. ' Note that this isn't recursive... although it could be...
varFileList = fcnGetFileList(strFolder)
If Not IsArray(varFileList) Then
MsgBox "No files found.", vbInformation
Exit Sub
End If
' Now let's get all the details for these files ' and place them into an array so it's quick to dump to XL.
ReDim myResults(0 To UBound(varFileList) + 1, 0 To 5)
' place make some headers in the array
myResults(0, 0) = "Filename"
myResults(0, 1) = "Size"
myResults(0, 2) = "Created"
myResults(0, 3) = "Modified"
myResults(0, 4) = "Accessed"
myResults(0, 5) = "Full path"
Set FSO = CreateObject("Scripting.FileSystemObject")
' Loop through our files
For l = 0 To UBound(varFileList)
Set myFile = FSO.GetFile(CStr(varFileList(l)))
myResults(l + 1, 0) = CStr(varFileList(l))
myResults(l + 1, 1) = myFile.Size
myResults(l + 1, 2) = myFile.DateCreated
myResults(l + 1, 3) = myFile.DateLastModified
myResults(l + 1, 4) = myFile.DateLastAccessed
myResults(l + 1, 5) = myFile.Path
Next l
' Dump these to a worksheet
fcnDumpToWorksheet myResults
'tidy up
Set myFile = Nothing
Set FSO = Nothing
End Sub
Private Function fcnGetFileList(ByVal strPath As String, Optional strFilter As String) As Variant ' Returns a one dimensional array with filenames ' Otherwise returns False
Dim f As String
Dim i As Integer
Dim FileList() As String
If strFilter = "" Then strFilter = "."
Select Case Right$(strPath, 1)
Case "\", "/"
strPath = Left$(strPath, Len(strPath) - 1)
End Select
ReDim Preserve FileList(0)
f = Dir$(strPath & "\" & strFilter)
Do While Len(f) > 0
ReDim Preserve FileList(i) As String
FileList(i) = f
i = i + 1
f = Dir$()
Loop
If FileList(0) <> Empty Then
fcnGetFileList = FileList
Else
fcnGetFileList = False
End If
End Function
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
With sh
Range(.Cells(1, 1), .Cells(UBound(varData, 1) + 1, UBound(varData, 2) + 1)) = varData
.UsedRange.Columns.AutoFit
End With
Set sh = Nothing
Set wb = Nothing
End Sub
I've rewritten the code to pass your results array and a counter to the recursive function. The function fills the array and calls itself with any subfolders
Sub GetFileList()
Dim strFolder As String
Dim FSO As Object
Dim fsoFolder As Object
Dim myResults As Variant
Dim lCount As Long
Set FSO = 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 fsoFolder = FSO.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 fsoFolder, myResults, lCount
' Dump these to a worksheet
fcnDumpToWorksheet myResults
'tidy up
Set FSO = Nothing
End Sub
Private Sub FillFileList(fsoFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)
Dim i As Integer
Dim fsoFile As Object
Dim fsoSubFolder As Object
Dim fsoSubFolders As Object
'load the array with all the files
For Each fsoFile In fsoFolder.Files
lCount = lCount + 1
ReDim Preserve myResults(0 To 5, 0 To lCount)
myResults(0, lCount) = fsoFile.Name
myResults(1, lCount) = fsoFile.Size
myResults(2, lCount) = fsoFile.DateCreated
myResults(3, lCount) = fsoFile.DateLastModified
myResults(4, lCount) = fsoFile.DateLastAccessed
myResults(5, lCount) = fsoFile.Path
Next fsoFile
'recursively call this function with any subfolders
Set fsoSubFolders = fsoFolder.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