Function CreateBatchFile(sMessage As String) As String
'160711 strive4peace
'this code creates a batch file with a message in the current database directory.
'return path and filename if successfully written
On Error GoTo Proc_Err
CreateBatchFile = ""
Dim sPathFile As String _
,iFileNumber As Integer
sPathFile = CurrentProject.Path & "\SayMsg.Bat"
'delete the file that is already there
If Len(Dir(sPathFile)) > 0 Then
Kill sPathFile
DoEvents
End If
'get a handle
iFileNumber = FreeFile
'close file handle if it is open
'ignore any error from trying to close it if it is not
On Error Resume Next
Close #iFileNumber
On Error GoTo Proc_Err
'open file for output
Open sPathFile For Output As #iFileNumber
'write something
Print #iFileNumber, "@ECHO ON"
Print #iFileNumber, "@ECHO " & sMessage
Print #iFileNumber, "@Pause"
CreateBatchFile = sPathFile
'MsgBox "Done Creating " & sPathFile, , "Done"
Proc_Exit:
On Error Resume Next
'close the file
Close #iFileNumber
Exit Function
'ERROR HANDLER
Proc_Err:
MsgBox Err.Description _
,, "ERROR " & Err.Number _
& " CreateBatchFile"
Resume Proc_Exit
'if you want to single-step code to find error, CTRL-Break at MsgBox
'then set this to be the next statement
Resume
End Function
code to run it
Sub runCreateBatchFile()
'160711 strive4peace
'run a batch file
On Error GoTo Proc_Err
Dim sMessage As String _
,sPathFile As String _
,sCommand As String
sMessage = "This is a test"
sPathFile = CreateBatchFile(sMessage)
If Len(sPathFile) > 0 Then
'to run without the user seeing what is going on :
' Environ$("COMSPEC") is pathfile to cmd.exe
' sCommand = Environ$("COMSPEC") & " /c " & sPathFile ' & " &&pause"
'run and pause until user presses a key
sCommand = sPathFile
Shell sCommand,vbNormalFocus
End If
Proc_Exit:
On Error Resume Next
Exit Sub
'ERROR HANDLER
Proc_Err:
MsgBox Err.Description _
,, "ERROR " & Err.Number _
& " runCreateBatchFile"
Resume Proc_Exit
'if you want to single-step code to find error, CTRL-Break at MsgBox
'then set this to be the next statement
Resume
End Sub