简体   繁体   中英

VBA code to read a word doc

Is there any way to create a VBA code to read a word document via audio? as if the computer was reading the whatever is on the document. (of course all text).

I found this searching on google. http://vbadud.blogspot.com/2010/06/vba-how-to-convert-text-file-to-speech.html

Sub Speech_FromFile_Example() 

     Dim oVoice As SpVoice 
     Voice Object Dim oVoiceFile As SpFileStream 
     File Stream Object Dim sFile As String 
     File Name Set oVoice = New SpVoice 
     Set oVoiceFile = New SpFileStream


    oVoice.Speak "This is an example for reading out a file" 
    sFile = "C:\ShasurData\ForBlogger\SpeechSample.txt" 
    oVoiceFile.Open sFile 
    oVoice.SpeakStream oVoiceFile 

End Sub 

The code requires Microsoft Speech Object Library

VBA macro for Word:

Dim speech as SpVoice

Sub SpeakText()

On Error Resume Next

Set speech = New SpVoice

If Len(Selection.Text) > 1 Then 'speak selection
speech.Speak Selection.Text



SVSFlagsAsync + SVSFPurgeBeforeSpeak



Else 'speak whole document
speech.Speak ActiveDocument.Range(0, ActiveDocument.Characters.Count).Text



SVSFlagsAsync + SVSFPurgeBeforeSpeak



End If

Do
DoEvents

Loop Until speech.WaitUntilDone(10)

Set speech = Nothing

End Sub

Sub StopSpeaking()

'Based on a macro by Mathew Heikkila

'used to interrupt any running speech to text

On Error Resume Next

speech.Speak vbNullString, SVSFPurgeBeforeSpeak

Set speech = Nothing

End Sub

如果您使用的是 Windows 10,请小心 - 我有两个同名的库“Microsoft Speech Object Library” - 确保选择指向 Windows/system32/Speech/Common/sapi.dll 的库

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM