Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Heres and easy one!!

Status
Not open for further replies.

Newbie311

Programmer
Oct 6, 2003
30
GB
Hi chaps i need to count the Number of files in a folder.
Can anyone provide me with a simple bit of code to do so?

Thanks
 
dim counter as integer
dim myfile as string

counter = 0
do
myfile = Dir(folderpath)
counter = counter + 1
loop until myfile = ""


 
dim counter as integer
dim myfile as string
dim folderpath as string

folderpath = FOLDERPATH
counter = 0

do
myfile = Dir(folderpath)
counter = counter + 1
loop until myfile = ""

msgbox counter


 
Sorry about that, i posted the wrong code, heres correct code

dim counter as integer
dim myfile as string
dim folderpath as string

folderpath = 'write out the path of the folder where the files are
counter = 0
myfile = Dir(folderpath)

if myfile = "" then
msgbox "Folder is emptpy"
else
do
counter = counter + 1
myfile = Dir
loop until myfile = ""

msgbox counter
end if


 
This will give you a count of files (not including folders) in a specified folder:
[blue]
Code:
Sub CountFiles()
   With Application.FileSearch
     .LookIn = "c:\my documents"
     .FileType = msoFileTypeAllFiles
     If .Execute > 0 Then
       MsgBox .FoundFiles.Count & " files were found"
     Else
       MsgBox "No files were found"
     End If
   End With
End Sub
[/color]

Look up "FileSearch" in the help file for more info.
 
OR via VBScript

[vb]
Option Explicit

Function CountOfFiles(strFolderPath As String) As Double
Dim objFso As Object
Dim objFolder As Object

Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder(strFolderPath)

CountOfFiles = objFolder.Files.Count

End Function

Sub Tester()
MsgBox CountOfFiles("C:\ExcelFiles\Useful\")
End Sub
[/vb]

Or using WMI


[vb]
Sub CountFilesInFolder()
'// Enumerate All the Files in a Folder
'// Description
'// Returns a count of all the files in the Scripts folder.
'// (for example, C:\Scripts and D:\Scripts), files will be returned from each of these folders.
Const LookinDir = "AAddin_WIP"

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery("Select * from CIM_DataFile where Path = '\\" & LookinDir & "\\'")
'//
MsgBox colFiles.Count

End Sub
[/vb]

Ivan F Moala
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top