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

问题描述 投票:0回答:1

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 window dos
1个回答
0
投票

这似乎对我有用:

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
© www.soinside.com 2019 - 2024. All rights reserved.