提问人:bgr 提问时间:11/16/2023 最后编辑:Bernhard Erikssonbgr 更新时间:11/19/2023 访问量:44
EXCEL VBA Shell FINDSTR - 不希望弹出DOS窗口出现
EXCEL VBA Shell FINDSTR - Don't want pop up DOS window to appear
问:
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窗口在运行时不会出现或最小化,并且能够读取结果(未在文件中返回)。
答:
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
评论
.Run
FileSystemObject