Vba word стиль текста

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Document.Styles property (Word)

vbawd10.chm158007318

vbawd10.chm158007318

word

Word.Document.Styles

30784574-92d1-a2fa-1032-6e1f8bb79ccf

06/08/2017

medium

Document.Styles property (Word)

Returns a Styles collection for the specified document. Read-only.

Syntax

expression.Styles

expression A variable that represents a Document object.

Remarks

For information about returning a single member of a collection, see Returning an object from a collection.

Example

This example applies the Heading 1 style to each paragraph in the active document that begins with the word «Chapter.»

For Each para In ActiveDocument.Paragraphs 
 If para.Range.Words(1).Text = "Chapter " Then 
 para.Style = ActiveDocument.Styles(wdStyleHeading1) 
 End If 
Next para

This example opens the template attached to the active document and modifies the Heading 1 style. The template is saved, and all styles in the active document are updated.

Set tempDoc = ActiveDocument.AttachedTemplate.OpenAsDocument 
With tempDoc.Styles(wdStyleHeading1).Font 
 .Name = "Arial" 
 .Size = 16 
End With 
tempDoc.Close SaveChanges:=wdSaveChanges 
ActiveDocument.UpdateStyles

See also

Document Object

[!includeSupport and feedback]

Microsoft Word Style Object VBA (Visual Basic for Applications) example

Style

Represents a user-defined style. The Style object includes formatting attributes (such as font, font name, font color, paragraph alignment and paragraph spacing) as properties of the Style object. The Styles collection includes all the styles in the specified document Index (a positive integer), can be used to reference single style, Microsoft Word exposes WdBuiltinStyle constant which can be used to assign a predefined style. Style name are case sensitive hence should be remembered while referencing in the code. The following example modifies the font name of the user-defined style named “Color” in the active document.

Style Examples

public Sub ModifyFontStylemethod()
	  'Not recommended Active
	  ActiveDocument.Styles("InfoExtract").Font.Name = "Arial"
	  
	  'Recommended Strong Reference
	  Documents("MyDoc").Styles("InfoExtract").Font.Name = "Arial"
End Sub

Built in Style

public Sub BoldStylemethod()
   Documents("MyDoc").Styles(wdStyleHeading1).Font.Bold=True
End Sub

Styles collection

public Sub BaseStylemethod()
	'Get Vase Style
	Debug.Print Documents("MyDoc").Styles(1).BaseStyle
	
	'Get Local name of style
	Debug.Print Documents("MyDoc").Styles(1).NameLocal
End Sub

Range Object:

public Sub RangeStylemethod()
   oRange.Style = wdStyleNormal
End Sub

Selection Object:

public Sub SelectionStylemethod()
   Selection.Paragraphs(1).Style = wdStyleHeading1
End Sub

Add

public Sub AddStylemethod()
   Dim oStyle As Style
   Set oStyle = Documents("InfoExtractDoc").Styles.Add(Name:="InfoPara", Type:=wdStyleTypeCharacter)
   oStyle.Font.Bold=True
   Selection.Range.Style="InfoPara"
End Sub

Deleting

public Sub DeleteStylemethod()
   Documents("InfoExtractDoc").Styles("InfoPara").Delete
End Sub

Video: How to create/modify/apply styles in Microsoft Word:

Next>>Working with Special Symbols/Multi bytes Symbols in Word VBA

how to Microsoft Word images
Image: monticellllo/Adobe Stock

Styles are a huge part of working efficiently in Microsoft Word. If you work with files or templates that contain a lot of custom styles, you would welcome a list of them, but there’s no built-in Word feature that displays a list of all styles. In this Word tutorial, I’ll show you how to create a VBA procedure that inserts the name of all styles – custom, built-in or both – in the current document. You can print the document out for documentation purposes or for referencing.

SEE: Learn how much more Microsoft can do for you with this training bundle (TechRepublic Academy)

I’m using Microsoft 365 desktop on a Windows 64-bit system, but you can use earlier versions. For your convenience, you can download the demonstration .docm and .doc files. Word for the web doesn’t support VBA procedures.

What you need to know about the VBA procedure in Word

The following VBA procedure, aka macro, does a lot. First, the procedure prompts the user to choose between a list of built-in styles, custom styles or all styles. After the user responds, the procedure opens a new document and generates a list of the appropriate styles. Finally, the procedure displays the number of styles generated. The procedure does not save this Word document. It doesn’t sound like much considering the number of lines in the procedure.

Sub ListStyles()

'Generate a list of custom (1), built-in (2), or all Word styles (3)

'in the active document.

Dim doc As Document

Dim sty As Style

Dim inp As Integer

Dim i As Integer

i = 0

'Request input value from user.

On Error GoTo errHandler: 'Catches Cancel or X.

inp = InputBox("Please enter one of the following values 1, 2, or 3." _

& vbLf & vbLf & _

"1. Custom styles" & vbLf & _

"2. Built-in styles" & vbLf & _

"3. All styles", _

"Print a list of styles", 1)

'Check for invalid input value.

If inp >= 4 Or inp < 1 Then

MsgBox "Please enter a valid input value: 1, 2, or 3.", vbOKOnly, _

"Input Error"

Exit Sub

End If

On Error GoTo errHandler

Set doc = Documents.Add

'Cycle through styles in active document.

With doc

For Each sty In .Styles

If inp = 1 And sty.BuiltIn = False Then

.Range.InsertAfter sty.NameLocal & vbCr

i = i + 1

ElseIf inp = 2 And sty.BuiltIn = True Then

.Range.InsertAfter sty.NameLocal & vbCr

i = i + 1

ElseIf inp = 3 Then

.Range.InsertAfter sty.NameLocal & vbCr

i = i + 1

'No Else because earlier code catches any value other than 1, 2, or 3.

End If

Next sty

End With

MsgBox i & " styles found.", vbOKOnly

Set doc = Nothing

Exit Sub

errHandler:

If Err.Number = 13 Then Exit Sub

MsgBox Err.Number & " " & Err.Description

Set doc = Nothing

End Sub

About half of the code checks for input errors. After declaring a few variables, the code displays an input box prompting the user to enter one of the three values:

  • Custom styles
  • Built-in styles
  • All styles

The first On Error statement catches the error thrown if the user clicks Cancel or X. In this case, the errHandler block exits the procedure:

If Err.Number = 13 Then Exit Sub

By clicking Cancel or X, the code assumes the user doesn’t want to run the procedure after all so the code doesn’t display an explanatory message box.

If the user responds to the message box by entering a value, the procedure stores that input value in an integer variable named inp. If inp equals anything other than 1, 2 or 3, the code displays a message box requesting that the user enter one of the specified values – 1, 2 or 3 – and then the procedure quits.

When inp equals 1, 2 or 3, a For Each block runs more checks using If statements:

  • If inp equals 1, the user wants to print a list of custom styles. When the next check, sty.BuiltIn = False is true, sty is a custom style, so the statement adds the style name to the list and adds 1 to the i counter.
  • If inp equals 2, the user wants to print a list of built-in styles. When the check, sty.BuiltIn = True is true, sty is a built-in style, so the statement adds the style to the list and adds 1 to the i counter.
  • If inp equals 3, the user wants to print a list of all styles so there’s no check; the code adds the style to the list and adds 1 to the i counter.

The For Each ends when the procedure has cycled through all the styles in the active document. The last few statements display a message with the number of styles listed and then destroys the doc object and exits the Sub procedure. The error handling displays the number and description of any error. Most of the code is catching invalid input values, which is why there’s so much of it.

Now that you’ve had a look at the procedure, it’s time to enter it into a Word document.

SEE: Windows, Linux, and Mac commands everyone needs to know (free PDF) (TechRepublic)

How to enter the VBA procedure in Word

You will likely want to run this procedure in lots of documents and not just the same one. If that’s the case, consider creating a template file (.dotm). Another alternative is to add the procedure to the Personal.xlsb workbook, which grants access to the procedure from any open workbook file. The demonstration file is a macro-enabled file, .docm, because it’s the easiest to use for our purposes.

If you are using a ribbon version, be sure to save the workbook as a macro-enabled file. If you’re working in the menu version, you can skip this step. If you’re working on your own and aren’t using the downloadable demonstration file, add a custom style to your file so you can see how all three choices work.

To enter the procedure, press Alt + F11 to open the Visual Basic Editor. In the Project Explorer to the left, select ThisDocument. If you have more than one Word file open, be sure to select the right one. You can enter the code manually or import the downloadable .cls file. In addition, the procedure is in the downloadable .docm file. If you enter the code manually, don’t paste from this web page. Instead, copy the code into a text editor and then paste that code into ThisDocument. This will remove any phantom web characters that might cause errors.

Save the file and return to the Word document. You’re ready to run the VBA procedure to see how it works.

How to run the VBA procedure in Word

Now comes the easy part: Running the procedure. To do so, click the Developer tab and then click Macro in the Macros group. In the resulting dialog, choose ListStyles (Figure A) and click Run.

Figure A

Run the VBA procedure ListStyles in Word.

Run the VBA procedure ListStyles in Microsoft Word

The message box defaults to the first choice, 1. Custom styles (Figure B). Click OK without changing that input value.

Figure B

In Word, choose 1. Custom styles and click OK.

In Microsoft Word, choose 1. Custom styles and click OK.

As you can see in Figure C, the demonstration file has one custom style: MyCustomStyle. Be sure to save this file manually if you want to keep it for documentation purposes.

Figure C

The VBA procedure inserts the custom style into the active document and then displays the number of custom styles found in the current document—1.

The VBA procedure inserts the custom style into the active document.

Run the procedure again and choose 2 for built-in styles. Figure D shows the more than 300 results, If you don’t see ListStyles, you might be in the new document the procedure created during the first run. Be sure to return to your macro-enabled file.

Figure D

In Microsoft Word, there are more than 300 built-in styles.

In Microsoft Word, there are more than 300 built-in styles.

Continue to run the VBA procedure to see how it all works with other input values: Enter 3, click Cancel, enter 0 and 4, and so on.

You don’t want to work through all those steps to run this macro each time you need it. I recommend that you add it to the Quick Access Toolbar or a custom group. If you need help with that, read my TechRepublic articleHow to add Office macros to the QAT toolbar for quick access.

If you don’t know how to enter this procedure in Personal.xlsb so it’s available to all workbooks, read my TechRepublic article, How to create a VBA procedure that closes all open workbooks in Excel, which includes instructions for using Personal.xlsb.

Are you interested in learning more about VBA in Excel? See these resources in TechRepublic Academy:

  • Microsoft VBA Bundle
  • The Complete Microsoft Excel & VBA Bundle
  • Master Microsoft Excel Macros and Excel VBA
  • The Complete Excel, VBA, and Data Science Certification Training Bundle
title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Styles object (Word)

vbawd10.chm2349

vbawd10.chm2349

word

bc4688ce-5055-c135-a656-e58e31d8be42

06/08/2017

medium

Styles object (Word)

A collection of Style objects that represent both the built-in and user-defined styles in a document.

Remarks

Use the Styles property to return the Styles collection. The following example deletes all user-defined styles in the active document.

For Each sty In ActiveDocument.Styles 
 If sty.BuiltIn = False Then sty.Delete 
Next sty

Use the Add method to create a new user-defined style and add it to the Styles collection. The following example adds a new character style named «Introduction» and makes it 12-point Arial, with bold and italic formatting. The example then applies this new character style to the selection.

Set myStyle = ActiveDocument.Styles.Add(Name:="Introduction", _ 
 Type:=wdStyleTypeCharacter) 
With myStyle.Font 
 .Bold = True 
 .Italic = True 
 .Name = "Arial" 
 .Size = 12 
End With 
Selection.Range.Style = "Introduction"

Use Styles (Index), where Index is the style name, a WdBuiltinStyle constant or index number, to return a single Style object. You must exactly match the spelling and spacing of the style name, but not necessarily its capitalization. The following example modifies the font of the user-defined style named «Color» in the active document.

ActiveDocument.Styles("Color").Font.Name = "Arial"

The following example sets the built-in Heading 1 style to not be bold.

ActiveDocument.Styles(wdStyleHeading1).Font.Bold = False

The style index number represents the position of the style in the alphabetically sorted list of style names. Note that Styles(1) is the first style in the alphabetical list. The following example displays the base style and style name of the first style in the Styles collection.

MsgBox "Base style= " _ 
 & ActiveDocument.Styles(1).BaseStyle & vbCr _ 
 & "Style name= " & ActiveDocument.Styles(1).NameLocal

The Styles object is not available from the Template object. However, you can use the OpenAsDocument method to open a template as a document so that you can modify styles in the template. The following example changes the formatting of the Heading 1 style in the template attached to the active document.

Set aDoc = ActiveDocument.AttachedTemplate.OpenAsDocument 
With aDoc 
 .Styles(wdStyleHeading1).Font.Name = "Arial" 
 .Close SaveChanges:=wdSaveChanges 
End With

Use the OrganizerCopy method to copy styles between documents and templates. Use the UpdateStyles method to update the styles in the active document to match the style definitions in the attached template.

Methods

Name
Add
Item

Properties

Name
Application
Count
Creator
Parent

See also

Word Object Model Reference

[!includeSupport and feedback]

So, there are a few ways to make your code more expandable or reusable. You could use wildcard searches to minimize the actual number of searches required. Or you could put your text strings into an array that you loop through to keep the actual code to a minimum. For your purposes, and to make this as clear as possible, I haven’t done that. This just takes your searches and makes them actual search and replaces so that changes are only made when the text is found. In order to limit your searches to text on its own line, I’ve added the special «^p» find sequence. This searches for your text followed by a paragraph break. That’s not perfect, but it should be closer to what you’re looking for. If you’re still seeing only Heading 2 applied after you run this, it might be necessary to include a portion of the text of your document in your question to clarify exactly what it looks like.

Sub QOS_Headings()
Dim objDoc As Document
Dim head1 As Style, head2 As Style, head3 As Style, head4 As Style
'
' QOS_Headings Macro

' Converts section headings in eCTD to usable navigation headings in Word.

'

' Using variables here just simplifies the typing further on, and allows
' you to easily change, for instance, "Heading 4" to "My Personal Heading 4"
' if you were creating your own styles.

Set objDoc = ActiveDocument
' This code does *NOT* protect against the possibility that these styles don't
' appear in the document. That's probably not a concern with built-in styles,
' but be aware of that if you want to expand upon this for other uses.
Set head1 = ActiveDocument.Styles("Heading 1")
Set head2 = ActiveDocument.Styles("Heading 2")
Set head3 = ActiveDocument.Styles("Heading 3")
Set head4 = ActiveDocument.Styles("Heading 4")

' This searches the entire document (not including foot/endnotes, headers, or footers)
' for your text string. Putting "^p" at the end of the string limits it to text strings
' that fall at the end of a paragraph, which is likely the case as your headings sit on
' their own line. You might want to experiment with that. Note that putting ^p at the
' beginning of the text will NOT work; that will apply your style to the previous
' paragraph as well.
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2^p"
    With .Replacement
    .ClearFormatting
    .Style = head1
    End With
    ' Here we do the actual replacement. Based on your requirements, this only replaces the
    ' first instance it finds. You could also change this to Replace:=wdReplaceAll to catch
    ' all of them.
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With

With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S^p"
    With .Replacement
    .ClearFormatting
    .Style = head2
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.1^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.2^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.3^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.4^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.4.1^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.4.2^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.4.3^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.4.4^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.4.5^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.6^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.S.7^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P^p"
    With .Replacement
    .ClearFormatting
    .Style = head2
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.1^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.2^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.3^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.4^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.5^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.5.1^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.5.2^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.5.3^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.5.4^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.5.5^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.5.6^p"
    With .Replacement
    .ClearFormatting
    .Style = head4
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.6^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.7^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.P.8^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.A^p"
    With .Replacement
    .ClearFormatting
    .Style = head2
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.A.1^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.A.2^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.A.3^p"
    With .Replacement
    .ClearFormatting
    .Style = head3
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
With objDoc.Content.Find
    .ClearFormatting
    .Text = "3.2.R^p"
    With .Replacement
    .ClearFormatting
    .Style = head2
    End With
    .Execute Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceOne
End With
End Sub

One final suggestion: one way to get started with VBA programming is to use the macro recorder. It’s not perfect, but it will give you the basic structure of, for instance, a search and replace if you record yourself doing one.

Понравилась статья? Поделить с друзьями:
  • Vba word список папок
  • Vba word сохранить как pdf
  • Vba word сохранить все
  • Vba word создать папку
  • Vba word создание таблиц