Counting files in a directory

U

Ulf Nilsson

Hi,
In VBA, one can use "ActiveDocument.Words.Count" to count words in a
document. What do I use to count number of files in a directory? Do I have to
loop through and count or is there a command like Directory.Files.Count?

/ Ulf
 
J

Jean-Guy Marcil

Ulf Nilsson was telling us:
Ulf Nilsson nous racontait que :
Hi,
In VBA, one can use "ActiveDocument.Words.Count" to count words in a
document. What do I use to count number of files in a directory? Do I
have to loop through and count or is there a command like
Directory.Files.Count?

Here is one way of doing it:
Look up the Dir method. Then use it to loop through the files and increment
a counter.

--
Salut!
_______________________________________
Jean-Guy Marcil - Word MVP
(e-mail address removed)
Word MVP site: http://www.word.mvps.org
 
U

Ulf Nilsson

Hi,
I know about the Dir-method, but thought there was a simpler way of doing it.

/ Ulf
 
J

Jay Freedman

Ulf said:
Hi,
In VBA, one can use "ActiveDocument.Words.Count" to count words in a
document. What do I use to count number of files in a directory? Do I
have to loop through and count or is there a command like
Directory.Files.Count?

/ Ulf

Hi Ulf,

Set a reference (in Tools > References) to Microsoft Scripting Runtime. Then
use code like this:

Function FileCount(fldrName As String) As Long
Dim fso As FileSystemObject
Dim fldr As Folder

Set fso = New FileSystemObject
With fso
If .FolderExists(fldrName) Then
Set fldr = .GetFolder(fldrName)
FileCount = fldr.Files.Count
Set fldr = Nothing
Else
FileCount = -1
End If
End With
Set fso = Nothing
End Function

Sub Test_FileCount()
Dim strName As String

strName = "C:\"
MsgBox strName & " contains " & _
FileCount(strName) & " file(s)"
End Sub
 
U

Ulf Nilsson

Thanks Jay!
It works just fine!

When I set a reference to MS Scripting Runtime, will this setting be saved
within the file so others also get the macro to work? How does it work?

/ Ulf
 
J

Jean-Guy Marcil

Ulf Nilsson was telling us:
Ulf Nilsson nous racontait que :
Thanks Jay!
It works just fine!

When I set a reference to MS Scripting Runtime, will this setting be
saved within the file so others also get the macro to work? How does
it work?

Yes, the setting is saved in the template, so that any document created from
the template will have the reference set, unless you are referencing an
obscure library and that it does not exist on someone's computer. But I
believe that MS Scripting Runtime is always present.

--
Salut!
_______________________________________
Jean-Guy Marcil - Word MVP
(e-mail address removed)
Word MVP site: http://www.word.mvps.org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top