VBA要在列A中查找特定文件夹内的字符串,它包含几种类型的文件

时间:2013-10-16 09:15:41

标签: excel vba excel-vba

我需要一个符合以下要求的代码

  1. Excel工作表的A列包含一些字符串
  2. 我将指定一个文件夹来搜索这些字符串
  3. 在指定的文件夹中,会有子文件夹和几种类型的文件,例如:.txt,.c,.xml等。
  4. 4.i需要在整个文件夹结构中逐个搜索字符串并记录所有结果 A列中的搜索字符串C中B文件位置的文件中的Howmany出现

    谢谢

    以下代码将搜索在A列中输入的文件名,并将该位置存储在B

    我试过以下内容:

    选项明确

    Dim fso As New FileSystemObject
    Dim i As Long
    Dim fld As Folder
    Dim c As Range
    
    
    Sub Find_Path()
       Dim nDirs As Long, nFiles As Long, lSize As Currency
       Dim sDir As String, sSrchString As String, sItem As String
       Dim fldr As FileDialog
    
    
    111:
        With Application.FileDialog(msoFileDialogFolderPicker)
            .InitialFileName = "D:\Check\"   'ActiveWorkbook.Path & "\"
            .Show
               If .SelectedItems.Count = 0 Then
                MsgBox "Folder to search is  not selected"
                GoTo 111
               Else
                sDir = .SelectedItems(1)
               End If
      End With
    
    MsgBox "You have selected  : " & sDir, vbInformation
    
      'Application.Cursor = xlWait
      Application.DisplayStatusBar = True
      Application.StatusBar = "Please wait..."
    
        For Each c In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
    
    
         sSrchString = Range("A" & c.Row).Value
    
         lSize = FindFile(sDir, sSrchString, nDirs, nFiles)       
    
         If Str(nFiles) = 0 Then
    
           Range("B" & c.Row).Value = "Not Found in the Folder :   " & sDir
    
          End If
    
        Next
    Application.Cursor = xlDefault
    Application.StatusBar = False
    
    End Sub
    
    
    
    
    
    
    This will search for files in folder and sub folders. but i need to search string
    

1 个答案:

答案 0 :(得分:1)

这是你可以浏览文件的方法......只需为你要搜索的每个文件添加

Dim filenum, targetfile, Line
filenum = FreeFile
targetfile = "C:\Mytextfile.txt"
Open targetfile For Input As filenum
Do While Not EOF(filenum)
    Input #filenum, Line
    'if InStr(1, Line, yourSearchString) then 'check if your string is in this line
Loop
Close filenum