0
votes

H ey folks,

I need to find a specific string (formatted as heading 1) in a MS Word document via Excel VBA and then set a bookmark at that location. The latter part shouldn't be a problem as soon as I've got the range of the searched string.

However, I can't seem to figure out how to search for a string in Word using Excel VBA.

I tried the following (shortened):

Option Explicit

Sub exportWord(button As IRibbonControl)
Application.ScreenUpdating = False

Dim wrdDoc As Word.document
Dim wrdApp As Word.Application
Dim wrdLoc As String
wrdLoc = ThisWorkbook.Worksheets("Konfiguration").Range("changelogPath")

Set wrdApp = New Word.Application
wrdApp.Visible = True

Set wrdDoc = wrdApp.Documents.Open(wrdLoc)

Dim wrdRange As Word.Range
Dim searchString As String

Set wrdRange = wrdDoc.Range
searchString = "Test"

With wrdRange.Find
    .Text = searchString 
    .Replacement.Text = "Replacement Test"
    .wrap = wdFindContinue
    .ClearFormatting
    .Replacement.ClearFormatting
    .Replacement.Highlight = False
    .Execute Replace:=wdReplaceAll
End With
End Sub

This wouldn't actually do anything, but I just wanted to check of the finding works. It does not though and Excel just crashes without any VBA error or anything. Just says something amont of the lines of "Program not responding, the application has encountered a problem and will be closed down"

Does anyone have an idea why Excel would just crash without any proper error message? Or how to implemented a search in a Word document properly?

best regards,

daZza

1

1 Answers

0
votes

Tried something different and solved it with:

 For Each rngStory In wrdDoc.StoryRanges
        With rngStory.Find
            .Replacement.ClearFormatting
            .Text = "Ă„nderungen in Test12345"
            .Replacement.Text = "test"
            .wrap = wdFindContinue
            .ExecuteReplace:=wdReplaceAll
        End With
    Next