mamuesstack
mamuesstack

Reputation: 1271

How to programmatically create a formatted text in VBA?

I need to create a text (2 lines, multiple fonts) programmatically, that I later place in several tables (<100) of my document.

The only way I found out to solve this, is to create a Word.Paragraph and copy its Range to the cells. The problem with this approach is: while creating a Paragraph, it's added to the Document.

I want to create a formatted text like creating a string, all in the code without modifying the Document.

Upvotes: 1

Views: 4916

Answers (2)

LondonRob
LondonRob

Reputation: 78973

Could you use this on hidden text and this on deleting paragraphs?

Something like this:

Sub CreateNewWordDoc()
  Dim para As Word.Paragraph

  Set para = ActiveDocument.Paragraphs.Add
  para.Range.Font.Hidden = True
  ' Do your manipulation
  para.Range.Text = "Hello world"
  para.Range.Font.Name = "Tahoma"
  para.Range.Font.ColorIndex = wdBlue
  ' Now remove the paragraph as if it never existed!
  para.Range.Delete


End Sub

Upvotes: 1

Watki02
Watki02

Reputation: 4876

One approach I have used is to use HTML or richtext, which is essentially a string anyway. I am fairly sure Word can interpret either of these with the right com object settings.

Another approach I have tried is using the clipboard instead of a word object. You can do something like this:

(importing system.windows.forms)

Clipboard.SetText(Me.RichTextBox1.Rtf, TextDataFormat.Rtf)
ApplicationName.Selection.Paste()

Upvotes: 1

Related Questions