如何提示用户搜索关键字然后使用VBScript执行搜索?

时间:2016-06-17 20:16:12

标签: vbscript

我想通过InputBox提示用户输入关键字。一旦他们输入,比如小溪,然后按回车,我就会喜欢运行类似的东西:

dir *creek* /s

和' / s'可能不是最好的,因为我想只返回文件名,而/ s只返回文件名。

我发现Vbscripting to search for file via user input, calling functions to ask a series of questions to do tasks运行良好,但我试图让它更加用户友好,特别是让它能够使用通配符。

1 个答案:

答案 0 :(得分:1)

回答第二个问题“如何修改链接中的代码以使用通配符进行搜索”。有问题的代码是子程序:

Sub FindFile(searchname, searchdir) ' Two parameters: file name, search directory
    On Error Resume Next ' Enable error handling so we don't crash out on access denied errors
    Dim file, folder, subfolder
    For Each file In fso.GetFolder(searchdir).Files ' Process each file (as a file object) in the search directory
        If LCase(searchname) = LCase(file.Name) Then ' See if file name matches. Using LCase to convert both to lowercase for case insensitivity.
            ReDim Preserve fileslist(UBound(fileslist) + 1) ' If match found then increase array size by 1
            fileslist(UBound(fileslist)) = file.Path ' Store the file path in newly added array entry
        End If
    Next
    ' Now the recursive bit. For any subfolders in current search directory, call FindFile again
    ' with (1) the same file name originally passed in as "searchname", and (2) a new search 
    ' directory of the subfolder's name. FindFile then starts again on this new directory: finds files, 
    ' adds matches to the fileslist array, then does the same on each subfolder found. This 
    ' is how it searches each subfolder (and subfolders of subfolders... etc) in a directory
    For Each subfolder In fso.GetFolder(searchdir).SubFolders
        FindFile searchname, subfolder.Path
    Next
    On Error GoTo 0
End Sub

这里重要的一点是If LCase(searchname) = LCase(file.Name) Then行。我们可以将其更改为:

If instr(1,LCase(file.Name), LCase(searchname)) Then

如果searchname包含在字符串file.name中,它将返回true,该字符串用作通配符类型搜索。

以下一行:

fileslist(UBound(fileslist)) = file.Path

可以更改为:

fileslist(UBound(fileslist)) = file.Name 

为了获取名称而不是路径。