一个用递归实现的在指定目录查找指定文件的函数,源代码如下.问题是每次找到指定文件后,返回的文件数目有误.小弟百思不得其解,请各位高手指教!
Public Function SearchFile(ByVal fdir As String, _
                           ByVal fname As String, _
                           ByVal fpropty As VbFileAttribute, _
                           results() As String) As Long
'功能:在一个指定的文件夹里查找指定的文件
'入口参数: fdir  文件夹名 ;
'           fname  要查找的文件名;
'           fpropty  要查找的文件的属性(此参数为VB文件属性枚举常量)
'           results()  用于存放找到的文件路径的数组,此参数按引用传递,要求初始化数组上届为一,
'                      找到的结果从下标一开始存放在此数组中。
'出口参数: 找到的文件个数。
'完成日期:2004-03-12
On Error GoTo Err_Handler
Const ProgFiles = 17 'Program Files文件夹的属性代码
Dim temp As String
Dim tempt As String
Dim temps() As String
Dim counter As Long
Dim counter2 As Long
Dim tempi As Integer
'/记录在本目录搜索之前,已经找到的匹配的文件数
SearchFile = UBound(results)
tempi = SearchFile
'/
temp = Dir(fdir, vbDirectory)
If temp <> "" Then
   counter = 0
   ReDim temps(counter)
   temps(0) = temp
End If
While Not temp = ""
      If temp = fname Then
         SearchFile = SearchFile + 1
         ReDim Preserve results(SearchFile)
         results(SearchFile) = fdir & fname
      Else
         If Right(fdir, 1) = "\" Then
            If (GetAttr(fdir & temp) = vbDirectory Or GetAttr(fdir & temp) = ProgFiles) And InStr(temp, ".") = 0 Then
               SearchFile = SearchFile + SearchFile(fdir & temp & "\", fname, vbDirectory, results)
            End If
         Else
            If (GetAttr(fdir & "\" & temp) = vbDirectory Or GetAttr(fdir & temp) = ProgFiles) And InStr(temp, ".") = 0 Then
               SearchFile = SearchFile + SearchFile(fdir & "\" & temp & "\", fname, vbDirectory, results)
            End If
         End If
      End If
      '//恢复本目录搜索现场
      If Dir(fdir, vbDirectory) = temp Then
         temp = Dir()
      Else
         counter2 = 1
         tempt = Dir()
         Do
           counter2 = counter2 + 1
           tempt = Dir()
         Loop While Not temp = temps(counter2 - 1)
         temp = tempt
      End If
      '//
      counter = counter + 1
      ReDim Preserve temps(counter)
      temps(counter) = temp
Wend
'/如果在本目录没找到,则将SearchFile设置为零
If tempi = SearchFile Then
   SearchFile = 0
End If
'/
Exit Function
Err_Handler:
   SearchFile = 0
End Function

解决方案 »

  1.   

    ☆☆☆☆☆☆☆☆☆☆☆☆☆  
    ☆☆☆☆☆    ☆        
        ☆    ☆☆☆☆☆☆  
        ☆    ☆        ☆  
        ☆    ☆  ☆    ☆  
        ☆    ☆  ☆    ☆  
        ☆    ☆  ☆    ☆  
        ☆    ☆  ☆    ☆  
    ☆  ☆        ☆☆      
      ☆☆      ☆    ☆    
            ☆☆        ☆