Simple VBA macro to copy text from docA to docB

Hi, 

I am using this simple VBA macro to extract the text is select with the mouse from the active document into a new document

strMytext = Selection.Range.Text
Selection.Copy
Documents.Add
Selection = strMytext

The problem is that when I select text from more than one row in a Word table, the script also copies the text that is present into columns I have not selected.

I have tried using 

strMytext = Selection.Text

instead, but then the script only copies the text from the first row of the selection (it does not copy text from multiple manually-selected rows in the table(s)

How do I copy only the text in the columns AND rows I have selected?

Thanks in advance for your help!

Answer
Answer

If part of a table is selected, the .Range of the selection will extend from the top leftmost cell that is selected through the whole of the rows until the bottom rightmost cell that is selected.

That, of course, is what you have discovered, and the only way around it is going to be to use a more complex method, but, it is going to depend on just to where you want the information copied.

Dim docSource as Document

Dim docTarget as Document

Dim trange as Range

Dim i As Long

Dim crange and Range

Set docSource = ActiveDocument

Set docTarget = Documents.Add

docSource.Activate

For i = 1 To Selection.Cells.count
    Set crange = Selection.Cells(i).Range

    crange.End = crange.End - 1

    Set trange = DocTarget.Range

    trange.Collapse wdCollapseEnd
    trange.FormattedText = crange.FormattedText & vbCr
Next i

Hope this helps,
Doug Robbins - MVP Office Apps & Services (Word)
dougrobbinsmvp@gmail.com
It's time to replace ‘Diversity, Equity & Inclusion’ with ‘Excellence, Opportunity & Civility’ - V Ramaswamy

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated October 5, 2021 Views 504 Applies to: