none
VBA Word - Run Macro on Newly Created Document RRS feed

  • Question

  • Hi friends,

    I am trying to run a macro on a new target document.

    Currently the macro copies words found in the document into a new document.

    I want the macro to continue working on the newly created target document.

    I used switch windows but that didnt work,

    Sub CopyWords() Dim oDocMain As Document Dim oDocNew As Document Dim oRange As Range Application.ScreenUpdating = False Set oDocMain = ActiveDocument Set oDocNew = Documents.Add With oDocMain Set oRange = .Range With oRange.Find .Text = "Apple" While .Execute oDocNew.Range.InsertAfter oRange & vbCr oRange.Collapse wdCollapseEnd Wend End With End With '-------------------------------------- ' Now Switch to Newly created document and do this

    Windows("oDocNew").Activate Selection.Find.ClearFormatting Selection.Find.Replacement.ClearFormatting With Selection.Find .Text = "App" .Replacement.Text = "Cherry" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End With Selection.Find.Execute Replace:=wdReplaceAll End Sub


    thank you for any ideas


    Cheers Dan :)


    Tuesday, October 4, 2016 4:03 PM

Answers

  • You are using a document object, so change this line 

    Windows("oDocNew").Activate

    to

    oDocNew.Activate

    oDocNew does not have the name "oDocNew" which is what your code is looking for.

    • Marked as answer by Dan_CS Tuesday, October 4, 2016 5:26 PM
    Tuesday, October 4, 2016 5:10 PM

All replies

  • You are using a document object, so change this line 

    Windows("oDocNew").Activate

    to

    oDocNew.Activate

    oDocNew does not have the name "oDocNew" which is what your code is looking for.

    • Marked as answer by Dan_CS Tuesday, October 4, 2016 5:26 PM
    Tuesday, October 4, 2016 5:10 PM
  • Hello Bernie,

    yay this key little detail worked!

    Infact I used the macro recorder and thats where i got the windows activate from.

    It didn't work after the first time running macro.

    It's sorted now :)

    Have a great day.


    Cheers Dan :)

    Tuesday, October 4, 2016 5:26 PM