1

I need to insert two different text parts automatically into a newly generated file through an Excel Macro. This is an example of my code that I have.

First I clear allthe existing tabs to have a clean document, then I want to put "This text should be aligned on the left" aligned to the left and "This text should be aligned on the right" aligned to the right on the same line.

.Content.Paragraphs.TabStops.ClearAll
.Content.InsertAfter "This text should be aligned on the left"

.Content.Paragraphs.TabStops.Add Position:=NewPos, _
      Alignment:=wdAlignTabRight, _
      Leader:=wdTabLeaderLines

 .Content.InsertAfter "This text should be aligned on the right"
 .Content.InsertParagraphAfter

With this command I manage to generate a Tabstop in Word, but I don't seem able to position it, or to make "This text should be aligned on the right" align to the right.

In the end it should look like this:

The two text parts should be generated by VBA and aligned this way.

picture

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
martiong
  • 11
  • 1
  • 4

1 Answers1

2

Is below code working for you?

Sub AlignLeftAndRight()
    Selection.ParagraphFormat.TabStops.Add Position:=CentimetersToPoints(16) _
        , Alignment:=wdAlignTabRight, Leader:=wdTabLeaderSpaces
    Selection.TypeText Text:="This text should be aligned on the left"
    Selection.EndKey Unit:=wdLine
    Selection.TypeText Text:=vbTab & "This text should be aligned on the right"
End Sub
Kokkie
  • 546
  • 6
  • 15
  • Thanks for the fast answer. Whenever I try to launch it, I get the error message "Compile error: Sub or Function not defined". Afterwards the CentimetersToPoints is highlighted. – martiong Jul 23 '14 at 11:57
  • At least the Sub-procedure works on Word 2010. Which version are you using? – Kokkie Jul 24 '14 at 09:13
  • 1
    Old thread, but for those who find it, CentimetersToPoints isn't part of Excel 2007 (at least on my install) but if you google "cm to points" you find the factor is 28.3464567 so you can replace CentimetersToPoints(16) with 16*28.3464567 or write your own conversion function. – buttonsrtoys Nov 15 '14 at 15:09