views:

893

answers:

5

Using VBA in MS Office, how do I add text to the Windows clipboard so that it will paste into Word as a table?

A: 

Have you tried formatting it as a HTML table?

mkoeller
Doesn't work. You need to tell the clipboard it's an HTML table when you copy it for that to work.
Chris B.
A: 

It's been a while since I've done any Windows programming, but I seem to recall that you register the format of the object. In fact, you can register multiple objects of different formats and the pasting application can choose between them (such as with Word's Paste Special option).

I would try to create a Word table object, fill it's cells with your data and then copy that onto the clipboard.

staticsan
+3  A: 

The Windows clipboard supports multiple formats. When you want to place things in the clipboard, you make one or more calls to RegisterClipboardFormat() telling it the formats of the objects you will be placing on the clipboard, followed by calls to SetClipboardData() which actually places the data into the clipboard.

If you want to be able to paste a Table into Word, then HTML is the easiest format to work with. Just copy an HTML table onto the clipboard, and it will paste correctly into Word, provided that you first register the clipboard data as an HTML object.

I'd give you some code, but it's easiest to just reference an example on MSDN:

How to add HTML code to the clipboard using Visual Basic

This page even shows an example of copying an HTML table onto the clipboard.

Kluge
A: 

Kluge answer is correct but this different article on MSDN has better code that is easier to re-use: http://blogs.msdn.com/jmstall/archive/2007/01/21/html-clipboard.aspx

namenlos
A: 

The Clipboard is great... But something seems a little sketchy about using it to hold the output from your program to paste into Word. What is it that you're trying to do that you probably should be doing some other way?