rodrigocf
rodrigocf

Reputation: 2099

Copy X amount of words to clipboard in word with VBA

I need a word macro that either highlights the first 2500 words so I can later copy them to an external application or to copy those 2500 words to the clipboard directly.

After some research I have been able to find examples of similar things but it starts copying when it finds a certain word and ends in another word, not by amount of words.

Any ideas on how to copy the first x amount of words?

Upvotes: 0

Views: 263

Answers (2)

Dan Donoghue
Dan Donoghue

Reputation: 6206

I see two options, 1 will take the first 2,500 words and put it in a string for you for later use in the code, the second option will just select and copy the first 2,500 words

Sub PutInVariable()
Dim MyArr As Variant, MyString As String
MyArr = Split(ThisDocument.Content.Text, " ")
ReDim Preserve MyArr(2499)
MyString = Join(MyArr, " ")
End Sub


Sub SelectAndCopy()
Selection.HomeKey Unit:=wdLine
Selection.MoveRight Unit:=wdWord, Count:=2500, Extend:=wdExtend
Selection.Copy
End Sub

Upvotes: 0

Bernard Saucier
Bernard Saucier

Reputation: 2270

Here's a small example of one would do this :

Sub HighlightFirst2500()

    counter = 0
    For Each w In ThisDocument.Words
        If w Like "*[0-z]*" Then
            counter = counter + 1
            If counter >= 2500 Then
                Exit For
            End If
        End If
        If counter = 1 Then
            w.Select
        Else
            Selection.Extend
        End If
        w.HighlightColorIndex = wdYellow
    Next w

    Selection.Copy

    MsgBox "The first " & counter & " words were highlighted in yellow AND added to the clipboard!"

End Sub

So basically,

  1. For each word in this document
  2. If it LOOKS like a word (or a number), increment the counter
  3. Highlight the word and add it to the selection even if it doesn't look like a word
  4. If the counter busts the limit, exit the loop early
  5. Copy everything that is selected

Upvotes: 1

Related Questions