How can I execute a command and wait for it to return?

I'm looking for something real basic that will allow me  to execute a windows command inside my VB program and wait for it to return. I'm currently using something like:

cmdStr = "dir /s /b>files.txt"

My problem is that when I try to open the files.txt file for reading, the actual dir command hasn't finished. Is there a way to get Shell to block until the command running is completed? Thanks very much for any help!
Who is Participating?
From VBNet (

Option Explicit

' Copyright ©1996-2006 VBnet, Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce
'               or publish this code on any web site,
'               online service, or distribute as source
'               on any media without express permission.

Private Const WAIT_INFINITE = -1&
Private Const SYNCHRONIZE = &H100000

Private Declare Function OpenProcess Lib "kernel32" _
  (ByVal dwDesiredAccess As Long, _
   ByVal bInheritHandle As Long, _
   ByVal dwProcessId As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" _
  (ByVal hHandle As Long, _
   ByVal dwMilliseconds As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" _
  (ByVal hObject As Long) As Long  

Private Sub Command1_Click()

   Dim hProcess As Long
   Dim taskId As Long
   Dim cmdline As String
   cmdline = "notepad.exe"
   taskId = Shell(cmdline, vbNormalFocus)
   hProcess = OpenProcess(SYNCHRONIZE, True, taskId)
   Call WaitForSingleObject(hProcess, WAIT_INFINITE)
   CloseHandle hProcess
   MsgBox "The shelled app has ended."

End Sub
You could use a loop after that. Something like:

Variable = Dir("Files.txt")
Do While Variable = ""

Or something like that.

If you do that, I would suggest a doevents inside of the loop, to make sure it does not lock up completely.
Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
wshShell.Run environ("COMSPEC") & " /c dir /s /b>files.txt",0, true
Set wshShell = Nothing
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.