EXCEL VBA Shell FINDSTR - 不希望弹出DOS窗口出现

EXCEL VBA Shell FINDSTR - Don't want pop up DOS window to appear

提问人:bgr 提问时间:11/16/2023 最后编辑:Bernhard Erikssonbgr 更新时间:11/19/2023 访问量:44

问:

Windows 10 我在 EXCEL 宏中有 VB 代码,该代码在文本文件中搜索值并返回匹配项。问题是在执行时弹出一个DOS窗口。我不希望出现这个窗口(或者如果它必须出现,请在某处最小化)。我做过很多宏编码,但据我所知,并不是真正的技术。这是我拥有的代码,它正在工作,但显示DOS窗口。它对文本文件中的 USERNAME 值进行不区分大小写的搜索。我需要获得结果并通读它们。感谢所有帮助,但我希望它不会太技术化或过于激烈。谢谢!

theCommand = "findstr /I /P "
theCommand = theCommand & " " & USERNAME & " " & ACTIVEEMPLOYEESLISTFILE

Set oShell = Nothing
Set oExec = Nothing
Set oOutput = Nothing
        
Set oShell = CreateObject("WScript.Shell")

Set oExec = oShell.Exec(theCommand)
Set oOutput = oExec.StdOut

While Not oOutput.AtEndOfStream
    recordLine = oOutput.readline
    MsgBox recordLine
Wend

我只是希望DOS窗口在运行时不会出现或最小化,并且能够读取结果(未在文件中返回)。

Excel VBA 窗口 命令行界面

评论

1赞 Tim Williams 11/17/2023
以前: stackoverflow.com/questions/32297699/...
0赞 Bart McEndree 11/17/2023
我发现这个类似的问题 stackoverflow.com/questions/32297699/......
1赞 Tim Williams 11/17/2023
如果您无法隐藏窗口,那么也许您可以使用VBA来搜索文件?
0赞 CHill60 11/17/2023
我同意蒂姆·威廉姆斯(Tim Williams)的观点-如果要捕获结果,最好在VBA中阅读文件-示例 stackoverflow.com/questions/17275040/...
0赞 Ron Rosenfeld 11/17/2023
正如在其他注释中的参考文献中所指出的,您需要使用该方法并将结果写入临时文件,以便能够防止这种情况发生。您可以使用 读取临时文件,然后删除临时文件。.RunFileSystemObject

答:

0赞 Tim Williams 11/18/2023 #1

这似乎对我有用:

Sub TestSearch()
    
    Const OUTPUT_FILE As String = "C:\Temp\output.txt" 'file for results
    '2>&1 - capture stderr in same file as stdout
    Const CMD As String = "cmd.exe /c findstr /I /P ""<lookfor>"" ""<infile>"" > ""<resultsfile>"" 2>&1"
    Dim runThis As String
    'build the command by replacing tokens
    runThis = Replace(CMD, "<lookfor>", "failed")
    runThis = Replace(runThis, "<infile>", "C:\Temp\tester.log")
    runThis = Replace(runThis, "<resultsfile>", OUTPUT_FILE)
    Debug.Print runThis
    With CreateObject("WScript.Shell")
        .Run runThis, 0, True
    End With
    
    Debug.Print FileText(OUTPUT_FILE) 'show the results
    
End Sub

'return all the text from a file
Function FileText(pth)
    With CreateObject("scripting.filesystemobject").OpenTextFile(pth)
        FileText = .readall()
        .Close
    End With
End Function