You will need to place the code in a Class module in order to sink the ListeningSession_Recognition event. The class module could be a userform too.
Add a new class module to your vba project and name the module :
CVoiceListener
1- Class Module code:
VBA Code:
Option Explicit
Private WithEvents ListeningSession As SpSharedRecoContext
Private Grammar As ISpeechRecoGrammar
Private Sub Class_Initialize()
If (ListeningSession Is Nothing) Then
Set ListeningSession = New SpSharedRecoContext
Set Grammar = ListeningSession.CreateGrammar(1)
Grammar.DictationLoad
End If
Grammar.DictationSetState (SpeechRuleState.SGDSActive)
End Sub
Private Sub ListeningSession_Recognition( _
ByVal StreamNumber As Long, _
ByVal StreamPosition As Variant, _
ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
ByVal Result As SpeechLib.ISpeechRecoResult)
Dim sMacro As String
Select Case LCase(Result.PhraseInfo.GetText)
Case "run nsw", "runnsw"
sMacro = "run_nsw"
Case "run vic", "runvic"
sMacro = "run_vic"
Case "run qld", "runqld"
sMacro = "run_qld"
' Case other states ...
End Select
If Len(sMacro) Then
Call Application.Run(sMacro)
End If
End Sub
2- Place the following code In a
Standard Module: (Run the
InitVoiceListener routine to initiate the voice recognition)
VBA Code:
Option Explicit
Private oVoice As CVoiceListener
Sub InitVoiceListener()
Set oVoice = New CVoiceListener
End Sub
Sub run_nsw()
MsgBox "You ran: " & vbLf & "run_nsw"
End Sub
Sub run_vic()
MsgBox "You ran: " & vbLf & "run_vic"
End Sub
Sub run_qld()
MsgBox "You ran: " & vbLf & "run_qld"
End Sub
The above assumes the following:
1- You have already set a reference to the Microsoft Speech Object Library via Tools\References.
2- The names of the macros you want to run with your voice contain an uderscore in the middle.
3- You call the macros saying : Run NSW , Run VIC, Run QLD ... etc