Using VBA to Copy Text into an Office document

106 23
Charles wrote, "I'm preparing a document for a code review using Word. Is it possible to place a macro button in a Word document that opens a source code document, grabs a certain number of lines and then displays those lines in a popup window?"

It wasn't entirely clear to me exactly what Charles wanted to do. Did he want to copy the source code into Word? Or just display it? Did he want to display pre-selected chunks of source code or did he want to select at random and then display it?

I decided that, especially for the benefit or others, I would simply cover all the options I could think of.

(Note: This article is written using Word 2010.)

Opening a Source Code Document Using VBA

One advantage of VB.NET (which is shared with other .NET languages like C# and even non .NET languages like Java) is that the source code is in a simple text file. It will have a file qualifier like ".vb" or ".cs", but it's still just text. That makes it easy to open it in Word or another Office application. Here's the code that does it:

Sub GrabSourceText()'' GrabSourceText Macro' Opens a source code file, selects text,' and copies it into a Word document.'ChangeFileOpenDirectory _"C:\<your file path>\"Documents.Open FileName:="Form1.vb", _ConfirmConversions:=False, _ReadOnly:=True, AddToRecentFiles:=False, _PasswordDocument:="", _PasswordTemplate:="", Revert:=False, _WritePasswordDocument:="", _WritePasswordTemplate:="", _Format:=wdOpenFormatAuto, XMLTransform:=""End Sub

This statement was simply "recorded" in Word using the "Record Macro" feature. The macro recorder will use all of the parameters whether they're needed or not. I find it easier to simply keep them rather than worry about which ones I might be able to delete. In this case, only the ReadOnly parameter was changed because it's just not a good idea to change your VB.NET source code using Word.

You can save the source code as a text file in your VB.NET project folder, but that doesn't create a problem because Visual Studio simply ignores it. But ReadOnly prevents Word from saving the actual VB.NET source code file, even if you try.

--------
Click Here to display the illustration
--------


You will probably want to make sure that you run this macro from a Word document that has been previously saved. If you just open a new document and then run the macro without saving the document first, the new document isn't kept and the only document that remains open is the source code document.

Displaying the Source Code

Charles said he wanted to open the source code in a popup window. The code above opens the source code in another Word document. Word doesn't provide a window that you can just open and display text, however. But Windows does! NotePad works fine for this purpose. Here's the code to do the same thing with NotePad instead of Word.

Sub startNotepad()'' startNotepad Macro' Start Notepad and read a source code file'retVal = Shell("NOTEPAD.EXE " & _"C:\<your file path>\Form1.vb", _vbNormalFocus)End Sub
Note that the file name, Form1.vb, is part of the command here.

This creates a nice popup NotePad window:

--------
Click Here to display the illustration
--------


One problem with NotePad is that you can't control it from Word. That is, once the document is displayed in NotePad, you can't do much else with the document using VBA code. (You can always do it manually in NotePad, but the point here is to write code that will do it.) So let's return to displaying the source code in a Word document (the top code example) and see what else we can do.

Charles said he wanted to display "a certain number of lines". I'm not sure how he wanted to locate those lines in the source code (Count down from the top?) but the usual technique is to embed some identifying text in the source code. For example, if you had a long source document, you could embed a comment:
' Display Starting Here
And then search for it using VBA. Or, you could just use the names already in the code. For example, here's the VBA code to search for the NewClass class in the source:

x = Selection.Find.Execute(FindText:="NewClass")
--------
Click Here to display the illustration
--------


Charles also said he wanted to use a "macro button" to display the code. He'll need more than that since there has to be a way to select what code he wants to display. One way to do this would be to display a user form with different, pre-selected locations in the code. The Click event for a List control in the Form can then use basically the same code that we used before.

--------
Click Here to display the illustration
--------


Private Sub lbxLocationList_Click()Select Case lbxLocationList.ValueCase "Form1"ChangeFileOpenDirectory _"C:\<your file path>\"Documents.Open FileName:="Form1.vb", _ConfirmConversions:=False, _ReadOnly:=True, AddToRecentFiles:=False, _PasswordDocument:="", _PasswordTemplate:="", Revert:=False, _WritePasswordDocument:="", _WritePasswordTemplate:="", _Format:=wdOpenFormatAuto, XMLTransform:=""x = Selection.Find.Execute(FindText:="Form1"). . .End SelectEnd Sub
One tiny, but very important change that has to be made to make this work is to make the ShowModal property for the UserForm equal False. Otherwise, the application crashes in a lot of cases because Word tries to close a temporary form when the Documents.Open statement executes.
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.