title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
ParagraphFormat.Alignment property (Word) |
vbawd10.chm156434533 |
vbawd10.chm156434533 |
word |
Word.ParagraphFormat.Alignment |
637e83e0-813e-1a8d-18f2-6a8d41dc47af |
06/08/2017 |
medium |
ParagraphFormat.Alignment property (Word)
Returns or sets a WdParagraphAlignment constant that represents the alignment for the specified paragraphs. Read/write.
Syntax
expression.Alignment
expression Required. A variable that represents a ‘ParagraphFormat’ object.
Remarks
Some of the constants listed above may not be available to you, depending on the language support (U.S. English, for example) that you’ve selected or installed.
See also
ParagraphFormat Object
[!includeSupport and feedback]
I Have excel workbook which maintains data of my customers Like address & Due amount. I am writing a VBA code in excel which will generate letter to each of the customer for the due amounts. I cannot use mailmerge because of the complexity of the letter. I am using following codes to add paragraphs
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add
wrdDoc.content.InsertAfter "----------"
wrdDoc.content.InsertParagraphAfter
Now I need to change alignment of paragraphs. The paragraphs in body of letter are to be justified while some paragraphs like subject line are to be center aligned. I tried this code but its not working
1.
wrdDoc.Paragraphs(8).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
also
2.
wrdDoc.Paragraphs(8).Alignment = wdAlignParagraphCenter
What is the correct way doing this?
Regards
Shekhar
Returns or sets a ParagraphFormat
object that represents the paragraph settings for the specified range, selection, find or replacement operation, or style. Read/write.
Example
This example sets the paragraph formatting for the current selection to be right-aligned.
Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
This example sets paragraph formatting for a range that includes the entire contents of MyDoc.doc. Paragraphs in this document are double-spaced and have a custom tab stop at 0.25 inch.
Set myRange = Documents("MyDoc.doc").Content
With myRange.ParagraphFormat
.Space2
.TabStops.Add Position:=InchesToPoints(.25)
End With
This example modifies the Heading 2 style for the active document. Paragraphs formatted with this style are indented to the first tab stop and double-spaced.
With ActiveDocument.Styles(wdStyleHeading2).ParagraphFormat
.TabIndent(1)
.Space2
End With
This example finds all double-spaced paragraphs in the active document and replaces the formatting with 1.5-line spacing.
With ActiveDocument.Content.Find
.ClearFormatting
.ParagraphFormat.Space2
.Replacement.ClearFormatting
.Replacement.ParagraphFormat.Space15
.Execute FindText:="", ReplaceWith:="", _
Replace:=wdReplaceAll
End With
Using Excel VBA to create Microsoft Word documents
In these examples, we generate Microsoft Word Documents with various formatting features using
the Microsoft Excel VBA scripting language. These techniques can have many useful applications.
For instance if you have a list of data like a price or product list in Excel that you want to present
in a formatted Word Document, these techniques can prove useful.
In these examples, we assume the reader has at least basic knowledge of VBA, so we will not
go over basics of creating and running scripts. This code has been tested on Microsoft Word and Excel
2007. Some changes may be required for other versions of Word and Excel.
Writing to Word
Inserting a Table of Contents
Inserting Tabs
Inserting Tables
Inserting Bullet List
more on Inserting Tables
Multiple Features
Function that demonstrates VBA writing to a Microsoft Word document
The following code illustrates the use of VBA Word.Application object and related properties.
In this example, we create a new Word Document add some text.
'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running. 'Early Binding Dim wdApp As Word.Application Set wdApp = New Word.Application 'Alternatively, we can use Late Binding 'Dim wdApp As Object 'Set wdApp = CreateObject("word.Application") With wdApp .Visible = True .Activate .Documents.Add With .Selection .ParagraphFormat.Alignment = wdAlignParagraphCenter .Font.Bold = True .Font.Name = "arial" .Font.Size = 14 .TypeText ("My Heading") .TypeParagraph End With End With
Some VBA Vocabulary
ParagraphFormat
Represents all the formatting for a paragraph.
output in MS Word:
Inserting a Table of Contents into Word Document using Excel VBA
In this example, we generate a Table of Contents into a Word Document using Excel VBA
Sub sAddTableOfContents() Dim wdApp As Word.Application Set wdApp = New Word.Application 'Alternatively, we can use Late Binding 'Dim wdApp As Object 'Set wdApp = CreateObject("word.Application") Dim wdDoc As Word.Document Set wdDoc = wdApp.Documents.Add ' Note we define a Word.range, as the default range wouled be an Excel range! Dim myWordRange As Word.range Dim Counter As Integer wdApp.Visible = True wdApp.Activate 'Insert Some Headers With wdApp For Counter = 1 To 5 .Selection.TypeParagraph .Selection.Style = "Heading 1" .Selection.TypeText "A Heading Level 1" .Selection.TypeParagraph .Selection.TypeText "Some details" Next End With ' We want to put table of contents at the top of the page Set myWordRange = wdApp.ActiveDocument.range(0, 0) wdApp.ActiveDocument.TablesOfContents.Add _ range:=myWordRange, _ UseFields:=False, _ UseHeadingStyles:=True, _ LowerHeadingLevel:=3, _ UpperHeadingLevel:=1 End Sub
Some VBA Vocabulary
ActiveDocument.TablesOfContents.Add
The TablesOfContents property to return the TablesOfContents collection.
Use the Add method to add a table of contents to a document.
Some TablesOfContents Parameters
Range
The range where you want the table of contents to appear. The table of contents replaces the range, if the range isn’t collapsed.
UseHeadingStyles
True to use built-in heading styles to create the table of contents. The default value is True.
UpperHeadingLevel
The starting heading level for the table of contents. Corresponds to the starting value used with the o switch for a Table of Contents (TOC) field. The default value is 1.
LowerHeadingLevel
The ending heading level for the table of contents. Corresponds to the ending value used with the o switch for a Table of Contents (TOC) field. The default value is 9.
output Word Table in MS Word:
Write Microsoft Word Tabs
A function that writes tabbed content to a Microsoft Word Document. Note in each iteration, we change the
value of the leader character (characters that are inserted in the otherwise blank area created by the tab).
Public Sub sWriteMicrosoftTabs() 'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running. 'Early Binding Dim wdApp As Word.Application Set wdApp = New Word.Application 'Alternatively, we can use Late Binding 'Dim wdApp As Object 'Set wdApp = CreateObject("word.Application") With wdApp .Visible = True .Activate .Documents.Add For Counter = 1 To 3 .Selection.TypeText Text:=Counter & " - Tab 1 " ' position to 2.5 inches .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(2.5), _ Leader:=Counter, Alignment:=wdAlignTabLeft .Selection.TypeText Text:=vbTab & " - Tab 2 " ' position to 5 inches .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(5), _ Leader:=Counter, Alignment:=wdAlignTabLeft .Selection.TypeText Text:=vbTab & " - Tab 3 " .Selection.TypeParagraph Next Counter End With End Sub
Some VBA Vocabulary
.TabStops.Add
Use the TabStops property to return the TabStops collection. In the example above,
nprogram adds a tab stop positioned at 0, 2.5 and 5 inches.
output in MS Word:
Write Microsoft Word Tables
In this example, we generate a Microsoft Table using Excel VBA
Sub sWriteMSWordTable () 'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running. 'Early Binding Dim wdApp As Word.Application Set wdApp = New Word.Application 'Alternatively, we can use Late Binding 'Dim wdApp As Object 'Set wdApp = CreateObject("word.Application") With wdApp .Visible = True .Activate .Documents.Add With .Selection .Tables.Add _ Range:=wdApp.Selection.Range, _ NumRows:=1, NumColumns:=3, _ DefaultTableBehavior:=wdWord9TableBehavior, _ AutoFitBehavior:=wdAutoFitContent For counter = 1 To 12 .TypeText Text:="Cell " & counter If counter <> 12 Then .MoveRight Unit:=wdCell End If Next End With End With End Sub
Some VBA vocabulary
Table.Add
Table object that represents a new, blank table added to a document.
Table.Add properties
Range
The range where you want the table to appear. The table replaces the range, if the range isn’t collapsed.
NumRows
The number of rows you want to include in the table.
NumColumns
The number of columns you want to include in the table.
DefaultTableBehavior
Sets a value that specifies whether Microsoft Word automatically resizes cells in tables to fit the cells� contents (AutoFit). Can be either of the following constants: wdWord8TableBehavior (AutoFit disabled) or wdWord9TableBehavior (AutoFit enabled). The default constant is wdWord8TableBehavior.
AutoFitBehavior
Sets the AutoFit rules for how Word sizes tables. Can be one of the WdAutoFitBehavior constants.
output in MS Word:
Write Microsoft Word bullet list
In this example, we write with bullet list and outline numbers with Excel VBA
'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running. 'Early Binding Dim wdApp As Word.Application Set wdApp = New Word.Application 'Alternatively, we can use Late Binding 'Dim wdApp As Object 'Set wdApp = CreateObject("word.Application") With wdApp .Visible = True .Activate .Documents.Add ' turn on bullets .ListGalleries(wdBulletGallery).ListTemplates(1).Name = "" .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdBulletGallery).ListTemplates(1), _ continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior With .Selection .ParagraphFormat.Alignment = wdAlignParagraphLeft .Font.Bold = False .Font.Name = "Century Gothic" .Font.Size = 12 .TypeText ("some details") .TypeParagraph .TypeText ("some details") .TypeParagraph End With ' turn off bullets .Selection.Range.ListFormat.RemoveNumbers wdBulletGallery With .Selection .ParagraphFormat.Alignment = wdAlignParagraphLeft .TypeText ("some details") .TypeParagraph .TypeText ("some details") .TypeParagraph End With ' turn on outline numbers .ListGalleries(wdOutlineNumberGallery).ListTemplates(1).Name = "" .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdOutlineNumberGallery).ListTemplates(1), _ continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior With .Selection .ParagraphFormat.Alignment = wdAlignParagraphLeft .TypeText ("some details") .TypeParagraph .TypeText ("some details") End With End With
output in MS Word:
Another example of Writing Tables to Microsoft Word
In this example we will create a word document with 20 paragraphs. Each paragraph will have a header with a header style element
'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running. Dim wdApp As Word.Application Dim wdDoc As Word.Document Set wdApp = New Word.Application wdApp.Visible = True Dim x As Integer Dim y As Integer wdApp.Visible = True wdApp.Activate wdApp.Documents.Add wdApp.ActiveDocument.Tables.Add Range:=wdApp.Selection.Range, NumRows:=2, NumColumns:= _ 2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _ wdAutoFitFixed With wdApp.Selection.Tables(1) If .Style <> "Table Grid" Then .Style = "Table Grid" End If .ApplyStyleHeadingRows = True .ApplyStyleLastRow = False .ApplyStyleFirstColumn = True .ApplyStyleLastColumn = False .ApplyStyleRowBands = True .ApplyStyleColumnBands = False End With With wdApp.Selection For x = 1 To 2 ' set style name .Style = "Heading 1" .TypeText "Subject" & x .TypeParagraph .Style = "No Spacing" For y = 1 To 20 .TypeText "paragraph text " Next y .TypeParagraph Next x ' new paragraph .TypeParagraph ' toggle bold on .Font.Bold = wdToggle .TypeText Text:="show some text in bold" .TypeParagraph 'toggle bold off .Font.Bold = wdToggle .TypeText "show some text in regular front weight" .TypeParagraph End With
Some VBA vocabulary
TypeText
Inserts specified text at the beginning of the current selection. The selection is turned into an insertion point at the end of the inserted text.
If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as typing some text at the keyboard.
TypeParagraph
Insert a new blank paragraph. The selection is turned into an insertion point after the inserted paragraph mark. If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as pressing the Enter key.
output in MS Word:
Generating a Word table with VBA
'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running. Dim wdApp As Word.Application Dim wdDoc As Word.Document Dim r As Integer Set wdApp = CreateObject("Word.Application") wdApp.Visible = True Set wdDoc = wdApp.Documents.Add wdApp.Activate Dim wdTbl As Word.Table Set wdTbl = wdDoc.Tables.Add(Range:=wdDoc.Range, NumRows:=5, NumColumns:=1) With wdTbl .Borders(wdBorderTop).LineStyle = wdLineStyleSingle .Borders(wdBorderLeft).LineStyle = wdLineStyleSingle .Borders(wdBorderBottom).LineStyle = wdLineStyleSingle .Borders(wdBorderRight).LineStyle = wdLineStyleSingle .Borders(wdBorderHorizontal).LineStyle = wdLineStyleSingle .Borders(wdBorderVertical).LineStyle = wdLineStyleSingle For r = 1 To 5 .Cell(r, 1).Range.Text = ActiveSheet.Cells(r, 1).Value Next r End With
output in MS Word:
Option Explicit Dim wdApp As Word.Application Sub extractToWord() 'In Tools > References, add reference to "Microsoft Word 12 Object Library" before running. Dim lastCell Dim rng As Range Dim row As Range Dim cell As Range Dim arrayOfColumns arrayOfColumns = Array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "") Dim thisRow As Range Dim thisCell As Range Dim myStyle As String ' get last cell in column B lastCell = getLastCell() Set rng = Range("B2:H" & lastCell) 'iterate through rows For Each thisRow In rng.Rows 'iterate through cells in row row For Each thisCell In thisRow.Cells If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then ' do nothing ''frWriteLine thisCell.Value, "Normal" ''frWriteLine arrayOfColumns(thisCell.Column), "Normal" If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then End If Else myStyle = "Normal" Select Case thisCell.Column Case 2 myStyle = "Heading 1" Case 3 myStyle = "Heading 2" Case 4 myStyle = "Heading 3" Case Is > 5 myStyle = "Normal" End Select frWriteLine thisCell.Value, myStyle End If arrayOfColumns(thisCell.Column) = thisCell.Value Next thisCell Next thisRow End Sub Public Function getLastCell() As Integer Dim lastRowNumber As Long Dim lastRowString As String Dim lastRowAddress As String With ActiveSheet getLastCell = .Cells(.Rows.Count, 2).End(xlUp).row End With End Function Public Function frWriteLine(someData As Variant, myStyle As String) If wdApp Is Nothing Then Set wdApp = New Word.Application With wdApp .Visible = True .Activate .Documents.Add End With End If With wdApp With .Selection .ParagraphFormat.Alignment = wdAlignParagraphCenter .Style = myStyle .TypeText (someData) .TypeParagraph End With End With End Function
output in MS Word:
Alignment
Paragraph object exposes Alignment property which takes various constants to perform text alignment of selected paragraphs derived from WdParagraphAlignment enum. In this article we will see all available alignments:
Constants
- wdAlignParagraphLeft: Left-aligned, constant value is 0
- wdAlignParagraphCenter: Center-aligned, constant value is 1
- wdAlignParagraphRight: Right-aligned, constant value is 2
- wdAlignParagraphJustify: Fully justified, constant value is 3
- wdAlignParagraphDistribute: Paragraph characters are distributed to fill the entire width of the paragraph, constant value is 4
- wdAlignParagraphJustifyMed: Justified with a medium character compression ratio, constant value is 5
- wdAlignParagraphJustifyHi: Justified with a high character compression ratio, constant value is 7
- wdAlignParagraphJustifyLow: Justified with a low character compression ratio, constant value is 8
- wdAlignParagraphThaiJustify: Justified according to Thai formatting layout, constant value is 9
Code example
Public Sub ParagraphFormat() 'Declare Paragraph object Dim oParagraph As Paragraph 'Get paragraph Set oParagraph = ActiveDocument.Paragraphs(1) 'select paragraph text oParagraph.Range.Select 'Center align oParagraph.Alignment = wdAlignParagraphCenter 'Get paragraph Set oParagraph = ActiveDocument.Paragraphs(2) 'select paragraph text oParagraph.Range.Select 'Distribute oParagraph.Alignment = wdAlignParagraphDistribute 'Get paragraph Set oParagraph = ActiveDocument.Paragraphs(3) 'select paragraph text oParagraph.Range.Select 'Justify oParagraph.Alignment = wdAlignParagraphJustify 'Get paragraph Set oParagraph = ActiveDocument.Paragraphs(4) 'select paragraph text oParagraph.Range.Select 'Justify High oParagraph.Alignment = wdAlignParagraphJustifyHi 'Get paragraph Set oParagraph = ActiveDocument.Paragraphs(5) 'select paragraph text oParagraph.Range.Select 'Justify Low oParagraph.Alignment = wdAlignParagraphJustifyLow 'Get paragraph Set oParagraph = ActiveDocument.Paragraphs(6) 'select paragraph text oParagraph.Range.Select 'Justify medium oParagraph.Alignment = wdAlignParagraphJustifyMed 'Get paragraph Set oParagraph = ActiveDocument.Paragraphs(7) 'select paragraph text oParagraph.Range.Select 'Justify Left oParagraph.Alignment = wdAlignParagraphLeft 'Get paragraph Set oParagraph = ActiveDocument.Paragraphs(8) 'select paragraph text oParagraph.Range.Select 'Justify right oParagraph.Alignment = wdAlignParagraphRight 'Get paragraph Set oParagraph = ActiveDocument.Paragraphs(9) 'select paragraph text oParagraph.Range.Select 'Thai justify oParagraph.Alignment = wdAlignParagraphThaiJustify End Sub
Output
C# code example
private void btnParaAlignment_Click(object sender, RibbonControlEventArgs e) { //bind active document reference wordApp.Document oDocument = Globals.ThisAddIn.Application.ActiveDocument; //Paragraph object wordApp.Paragraph oParagraph = oDocument.Paragraphs[1]; //Select paragraph oParagraph.Select(); //Alignment Center oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphCenter; //Paragraph 2 oParagraph = oDocument.Paragraphs[2]; //Select paragraph oParagraph.Select(); //Alignment Left oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphLeft; //Paragraph 3 oParagraph = oDocument.Paragraphs[3]; //Select paragraph oParagraph.Select(); //Alignment Right oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphRight; //Paragraph 4 oParagraph = oDocument.Paragraphs[4]; //Select paragraph oParagraph.Select(); //Alignment Justify oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphJustify; //Paragraph 5 oParagraph = oDocument.Paragraphs[5]; //Select paragraph oParagraph.Select(); //Alignment Distribute oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphDistribute; //Paragraph 6 oParagraph = oDocument.Paragraphs[6]; //Select paragraph oParagraph.Select(); //Alignment Med oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphJustifyMed; //Paragraph 7 oParagraph = oDocument.Paragraphs[7]; //Select paragraph oParagraph.Select(); //Alignment Hi oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphJustifyHi; //Paragraph 8 oParagraph = oDocument.Paragraphs[8]; //Select paragraph oParagraph.Select(); //Alignment Low oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphJustifyLow; //Paragraph 9 oParagraph = oDocument.Paragraphs[9]; //Select paragraph oParagraph.Select(); //Alignment Thai oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphThaiJustify; }
VB.Net code example
Private Sub btnParaAlignExample_Click(sender As Object, e As RibbonControlEventArgs) Handles btnParaAlignExample.Click //bind active document reference Dim oDocument AS wordApp.Document oDocument = Globals.ThisAddIn.Application.ActiveDocument //Paragraph object wordApp.Paragraph oParagraph = oDocument.Paragraphs(1) //Select paragraph oParagraph.Select() //Alignment Center oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphCenter //Paragraph 2 oParagraph = oDocument.Paragraphs(2) //Select paragraph oParagraph.Select() //Alignment Left oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphLeft //Paragraph 3 oParagraph = oDocument.Paragraphs(3) //Select paragraph oParagraph.Select() //Alignment Right oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphRight //Paragraph 4 oParagraph = oDocument.Paragraphs(4) //Select paragraph oParagraph.Select() //Alignment Justify oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphJustify //Paragraph 5 oParagraph = oDocument.Paragraphs(5) //Select paragraph oParagraph.Select() //Alignment Distribute oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphDistribute //Paragraph 6 oParagraph = oDocument.Paragraphs(6) //Select paragraph oParagraph.Select() //Alignment Med oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphJustifyMed //Paragraph 7 oParagraph = oDocument.Paragraphs(7) //Select paragraph oParagraph.Select() //Alignment Hi oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphJustifyHi //Paragraph 8 oParagraph = oDocument.Paragraphs(8) //Select paragraph oParagraph.Select() //Alignment Low oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphJustifyLow //Paragraph 9 oParagraph = oDocument.Paragraphs(9) //Select paragraph oParagraph.Select() //Alignment Thai oParagraph.Alignment= wordApp.WdParagraphAlignment.wdAlignParagraphThaiJustify End Sub
Next >> Paragraph Spacing Microsoft Word Add-in code example