In a previous post about opening a word document and putting it in to a text box to 'preview' the content I came across a function on Ryan McCormick website I've started to tweak this for my own requirements.
I've added in a character count a if there's less than the selected number of characters it crashes (hence the added error handler) so added the if statement to sort that issue.Function getPreviewWordDocText(iFile) As String Dim oWord As Object Dim oWdoc As Object Dim docContent As String Dim numChar As Long ' Initialize Word Objects On Error GoTo Errhandler Set oWord = CreateObject("Word.Application") Set oWdoc = oWord.Documents.Open(iFile) ' Count number of characters in document numChar = oWdoc.Characters.Count ' If greater than 750 then select first 750 to preview. If numChar >= 750 Then docContent = oWdoc.Range(0, 750) Else ' If less than 750 select all characters to preview docContent = oWdoc.Content End If ' Return Document Content getPreviewWordDocText = docContent ' Completed go to clean up GoTo ExitMacro Errhandler: Select Case Err Case 4608: ErrMsg = "There is an error with the file you are previewing" & _ "Press OK to continue" Result = MsgBox(ErrMsg, vbOKOnly) GoTo ExitMacro Case Else: MsgBox "Error in preview macro # " & Err & " : " & Error(Err) GoTo ExitMacro End Select ExitMacro: ' Clear Memory oWdoc.Close oWord.Quit Set oWdoc = Nothing Set oWord = Nothing End Function
My main issue is now sometimes when opening the word document to count / read the text it waits in the background for a open read only / close / etc box if the word document is either open already or has not closed down correctly and someone still has it 'open'.
I've tried to play with opening it read only (as that all I need anyway) but not had any luck, should I be checking first to see if its open or can I just force open read only? Or should I be doing something completely different?