首先你可能需要等待wscript
完成命令的执行,所以我会尝试这样的事情
Sub test()
Dim cmdLine As Object
Dim result As Object
Set cmdLine = CreateObject("WScript.Shell")
Set result = cmdLine.Exec("%comspec% /C Find ""End of Report"" ""D:\test.csv"" | ECHO %ERRORLEVEL%")
Do While result.Status = 0
Application.Wait Now + TimeValue("00:00:01")
Loop
Debug.Print result.stderr.readall(), result.stdout.readall()
End Sub
为了看到该命令确实有效,您可以删除ECHO %ERRORLEVEL%
,您将得到真正的stdout
响应。stderr
.
Sub testA()
Dim cmdLine As Object
Dim result As Object
Set cmdLine = CreateObject("WScript.Shell")
Set result = cmdLine.Exec("%comspec% /C Find ""End of Report"" ""D:\test.csv""")
Do While result.Status = 0
Application.Wait Now + TimeValue("00:00:01")
Loop
Debug.Print result.stderr.readall(), result.stdout.readall()
End Sub
更新:如果您只需要在文件中找到某个文本,您可以使用以下方法
Sub TestC()
Debug.Print inFile("D:\Test.csv", "End of Report")
End Sub
Function inFile(fileName As String, searchText As String) As Boolean
Dim fileContent As String
Dim fileNo As Long
fileNo = FreeFile
Open fileName For Input As #fileNo
fileContent = Input(LOF(fileNo), fileNo)
Close #fileNo
If InStr(1, fileContent, searchText, vbTextCompare) > 0 Then
inFile = True
Else
inFile = False
End If
End Function
更新 2:根据评论,以下方法可能是您的问题的解决方案
Sub TestD()
Dim fileName As String
fileName = "D:\Test.csv"
If Not IsFileOpen(fileName) Then
Debug.Print inFile(fileName, "End of Report")
End If
End Sub
Function inFile(fileName As String, searchText As String) As Boolean
Dim fileContent As String
Dim fileNo As Long
fileNo = FreeFile
Open fileName For Input As #fileNo
fileContent = Input(LOF(fileNo), fileNo)
Close #fileNo
If InStr(1, fileContent, searchText, vbTextCompare) > 0 Then
inFile = True
Else
inFile = False
End If
End Function
Function IsFileOpen(fileName As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open fileName For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function