Word all fonts macro

Как мне сделать макрос который работал с шрифтами?

Написать макрос, в котором последовательно перебраются разные форматы шрифта и выводятся в Word в автоматическом режиме.


  • Вопрос задан

    более двух лет назад

  • 130 просмотров

Пригласить эксперта

Public Sub Font_Enumerate()
Dim i As Integer, oDoc As Document, oParagraph As Paragraph

Set oDoc = ThisDocument

oDoc.Bookmarks("EndOfDoc").Select ' Курсор - в конец документа

For i = 1 To Application.FontNames.Count
    DoEvents
    oDoc.Content.InsertParagraphAfter
    Set oParagraph = oDoc.Paragraphs(oDoc.Paragraphs.Count)
    oParagraph.Range.Text = "Studieren, studieren, studieren (c). " & vbTab & Application.FontNames(i)
    oParagraph.Range.Sentences(1).Font.Name = Application.FontNames(i)
Next i

Set oDoc = Nothing
End Sub

От Вас хотелось бы только узнать — кто автор бессмертной фразы, что генерируется кодом? )

Sub мой_макрос()
    For i = 1 To FontNames.Count
         Selection.Font.Name = FontNames(i)
         Selection.TypeText (vbCr + FontNames(i))
    Next i
End Sub


  • Показать ещё
    Загружается…

14 апр. 2023, в 23:01

10000 руб./за проект

14 апр. 2023, в 23:00

8000 руб./за проект

14 апр. 2023, в 20:37

5000 руб./за проект

Минуточку внимания

The macros below will display a list of all installed fonts. Note! If you have many fonts installed,
the macro may stop responding because of lack of available memory.

Sub ShowInstalledFonts()
Dim FontNamesCtrl As CommandBarControl, FontCmdBar As CommandBar, tFormula As String
Dim fontName As String, i As Long, fontCount As Long, fontSize As Integer
Dim stdFont As String
    fontSize = 0
    fontSize = InputBox("Enter Sample Font Size Between 8 And 30", _
        "Select Sample Font Size", 12)
    If fontSize = 0 Then Exit Sub
    If fontSize < 8 Then fontSize = 8
    If fontSize > 30 Then fontSize = 30
    Set FontNamesCtrl = Application.CommandBars("Formatting").FindControl(ID:=1728)
    If FontNamesCtrl Is Nothing Then
        Set FontCmdBar = Application.CommandBars.Add("TempFontNamesCtrl", _
            msoBarFloating, False, True)
        Set FontNamesCtrl = FontCmdBar.Controls.Add(ID:=1728)
    End If
    Application.ScreenUpdating = False
    fontCount = FontNamesCtrl.ListCount
    Documents.Add
    stdFont = ActiveDocument.Paragraphs(1).Range.Font.Name
    ' add heading
    With ActiveDocument.Paragraphs(1).Range
        .Text = "Installed fonts:"
    End With
    LS 2
    ' list font names and font example on every other line
    For i = 0 To FontNamesCtrl.ListCount - 1
        fontName = FontNamesCtrl.List(i + 1)
        If i Mod 5 = 0 Then Application.StatusBar = "Listing font " & _
            Format(i / (fontCount - 1), "0 %") & " " & _
            fontName & "..."
        With ActiveDocument.Paragraphs(ActiveDocument.Paragraphs.Count).Range
            .Text = fontName
            .Font.Name = stdFont
        End With
        LS 1
        tFormula = "abcdefghijklmnopqrstuvwxyz"
        If Application.International(wdProductLanguageID) = 47 Then
            tFormula = tFormula & "æøå"
        End If
        tFormula = tFormula & UCase(tFormula)
        tFormula = tFormula & "1234567890"
        With ActiveDocument.Paragraphs(ActiveDocument.Paragraphs.Count).Range
            .Text = tFormula
            .Font.Name = fontName
        End With
        LS 2
    Next i
    ActiveDocument.Content.Font.Size = fontSize
    Application.StatusBar = False
    If Not FontCmdBar Is Nothing Then FontCmdBar.Delete
    Set FontCmdBar = Nothing
    Set FontNamesCtrl = Nothing
    ActiveDocument.Saved = True
    Application.ScreenUpdating = True
    Application.ScreenRefresh
End Sub

Private Sub LS(lCount As Integer)
' adds lCount new paragraph(s) at the end of the document
Dim i As Integer
    With ActiveDocument.Content
        For i = 1 To lCount
            .InsertParagraphAfter
        Next i
    End With
End Sub

  • Home
  • Forum
  • VBA Code & Other Help
  • Word Help
  • Macro to List all Font & its size in a word document

  1. 01-16-2013, 11:43 AM


    #1

    Macro to List all Font & its size in a word document

    I need a Macro to list all the font name & its size in a word file — & list them
    This is required as per the Audit by the Project
    Can the below Macro be fine tuned for the same. The Below Macro list all the fonts other than arial & give me the page number where the font is located in the 300 page document. I need to modify the macro to give me all the fonts & its size in the new macro
    Sub FindAllFonts()
    Dim lWhichFont As Long
    Dim sTempName As String
    Dim sBuffer As String
    Dim newDoc As Document Dim p As Long
    Application.ScreenUpdating = False
    For lWhichFont = 1 To FontNames.Count
    sTempName = FontNames(lWhichFont)
    If sTempName <> «Arial» Then
    p = FindThisFont(sTempName)
    If p > 0 Then sBuffer = sBuffer & sTempName & » on page » & p & vbCrLf
    End If
    End If
    Next lWhichFont
    Set newDoc = Documents.Add
    Selection.TypeText Text:=sBuffer
    Application.ScreenUpdating = True
    End Sub
    Function FindThisFont(sName As String) As Long
    Selection.HomeKey Unit:=wdStory
    With Selection.Find
    .Text = «»
    .ClearFormatting
    .Font.Name = sName
    .Forward = True
    .Format = True
    If .Execute Then FindThisFont = Selection.Information(wdActiveEndPageNumber)
    End If
    End With
    End Function


  2. 01-17-2013, 09:34 AM


    #2

    Something like this:

    Sub FindAllFonts()
    Dim lngFontIndex As Long
    Dim strName As String
    Dim strReturn As String
    Dim oOutputDoc As Document
    Dim oRng As Word.Range
    Dim oCol As New Collection
    Dim lngIndex As Long
    Application.ScreenUpdating = False
    For lngFontIndex = 1 To FontNames.Count
      strName = FontNames(lngFontIndex)
      Set oRng = ActiveDocument.Range
      With oRng.Find
        .ClearFormatting
        .Text = ""
        .ClearFormatting
        .Font.Name = strName
        .Forward = True
        .Format = True
        .Wrap = wdFindStop
        While .Execute
          oRng.Select
          On Error Resume Next
          If oRng.Font.Size = 9999999 Then
            For Each oChr In oRng.Characters
              oCol.Add strName & " - " & oRng.Font.Size, strName & " - " & oRng.Font.Size
            Next oChr
          Else
            oCol.Add strName & " - " & oRng.Font.Size, strName & " - " & oRng.Font.Size
          End If
          On Error GoTo 0
          oRng.Collapse wdCollapseEnd
          If oRng.End + 1 = ActiveDocument.Range.End Then GoTo NextFont
        Wend
      End With
    NextFont:
    Next lngFontIndex
    Output:
    For lngIndex = 1 To oCol.Count
      strReturn = strReturn & oCol(lngIndex) & vbCr
    Next lngIndex
    Set oOutputDoc = Documents.Add
    oOutputDoc.Range.Text = strReturn
    Application.ScreenUpdating = True
    End Sub

    Last edited by macropod; 11-12-2018 at 02:15 AM.


  3. 01-17-2013, 11:19 AM


    #3

    Page Number not displayed in the Macro

    Sir,
    Thanks for the updated macro but The Output is not showing the Page no of the Fonts listed.

    The Output is only showing the Font & its Size — not the page no where it is located.


  4. 01-17-2013, 11:35 AM


    #4

    You didn’t say you wanted to list the page numbers. I don’t know why yet, but this macro is not processing text that is formatted with Theme Heading or Body font.

    Sub FindAllFonts()
    Dim lngFontIndex As Long
    Dim strName As String
    Dim strReturn As String
    Dim oOutputDoc As Document
    Dim oRng As Word.Range
    Dim oCol As New Collection
    Dim lngIndex As Long
    Dim oChr As Range
    Application.ScreenUpdating = False
    For lngFontIndex = 1 To FontNames.Count
      strName = FontNames(lngFontIndex)
      Set oRng = ActiveDocument.Range
      With oRng.Find
        .ClearFormatting
        .Text = ""
        .ClearFormatting
        .Font.Name = strName
        .Forward = True
        .Format = True
        .Wrap = wdFindStop
        While .Execute
          On Error Resume Next
          If oRng.Font.Size = 9999999 Then
            For Each oChr In oRng.Characters
              oCol.Add strName & " - " & oChr.Font.Size & " - page:" & oRng.Information(wdActiveEndPageNumber), _
                strName & " - " & oChr.Font.Size & " - page:" & oRng.Information(wdActiveEndPageNumber)
            Next oChr
          Else
            oCol.Add strName & " - " & oRng.Font.Size & " - page:" & oRng.Information(wdActiveEndPageNumber), _
              strName & " - " & oRng.Font.Size & " - page:" & oRng.Information(wdActiveEndPageNumber)
          End If
          On Error GoTo 0
          oRng.Collapse wdCollapseEnd
          If oRng.End + 1 = ActiveDocument.Range.End Then GoTo NextFont
        Wend
      End With
    NextFont:
    Next lngFontIndex
    For lngIndex = 1 To oCol.Count
      strReturn = strReturn & oCol(lngIndex) & vbCr
    Next lngIndex
    Set oOutputDoc = Documents.Add
    oOutputDoc.Range.Text = strReturn
    Application.ScreenUpdating = True
    End Sub

    Last edited by macropod; 11-12-2018 at 02:10 AM.


  5. 01-17-2013, 11:56 AM


    #5

    Thank you

    Sir,
    The MAcro is working perfectly fine.
    Thank you very much & sorry for the inconvienence caused


  6. 01-22-2018, 02:31 PM


    #6

    hey ! trying to use your program but i just want to display the sizes. so how can i remove the name of the font style from lngIndex.

    Thanks !

    Jess


  7. 01-22-2018, 05:06 PM


    #7

    This thread is 5 years old.

    Please start a new thread with a reference to this one.

    I expect the student to do their homework and find all the errrors I leeve in.



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

Please Note:
This article is written for users of the following Microsoft Word versions: 2007, 2010, and 2013. If you are using an earlier version (Word 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Word, click here: Creating a Document Font List.

Written by Allen Wyatt (last updated April 12, 2023)
This tip applies to Word 2007, 2010, and 2013


Word allows you to use the fonts that are installed on the system you are using. Fonts are installed within Windows, so that they are available not just to Word, but to all programs installed on your system.

When you are creating a document on your system, it is easy to know what fonts are being used—the list of fonts is limited to those available on the system. If you receive a document from a different person, however, the other person’s system may have different fonts installed than you do. This means that their Word document could be formatted with fonts you don’t even have on your system.

If you want to generate a list of fonts used within a document (as opposed to a list of fonts available on a system), you have a couple of choices. First of all, you can open the Word document in a text editor and look around in the parts of the document you don’t normally see in Word. Near the end of the file you should see a list of fonts used in the document. If you do this, however, you should be very careful to not make any changes to the Word document while it is open in your text editor. Doing so can easily make the document no longer usable in Word.

A Word-based solution is to simply look through each character in a document and check out what font is used to format the character. A character-by-character approach is necessary because each character could be formatted with a different font, and VBA doesn’t allow you to access a fonts collection in relation to the document itself—it seems that no such collection is maintained. Thus, the safest (and slowest) method is to simply step through each character and create your own list. The following VBA macro accomplishes the task:

Public Sub ListFontsInDoc()
    Dim FontList(199) As String
    Dim FontCount As Integer
    Dim FontName As String
    Dim J As Integer, K As Integer, L As Integer
    Dim X As Long, Y As Long
    Dim FoundFont As Boolean
    Dim rngChar As Range
    Dim strFontList As String

    FontCount = 0
    X = ActiveDocument.Characters.Count
    Y = 0
    ' For-Next loop through every character
    For Each rngChar In ActiveDocument.Characters
        Y = Y + 1
        FontName = rngChar.Font.Name
        StatusBar = Y & ":" & X
        ' check if font used for this char already in list
        FoundFont = False
        For J = 1 To FontCount
           If FontList(J) = FontName Then FoundFont = True
        Next J
        If Not FoundFont Then
            FontCount = FontCount + 1
            FontList(FontCount) = FontName
        End If
    Next rngChar

    ' sort the list
    StatusBar = "Sorting Font List"
    For J = 1 To FontCount - 1
        L = J
        For K = J + 1 To FontCount
            If FontList(L) > FontList(K) Then L = K
        Next K
        If J <> L Then
            FontName = FontList(J)
            FontList(J) = FontList(L)
            FontList(L) = FontName
        End If
    Next J

    StatusBar = ""
    ' put in new document
    Documents.Add
    Selection.TypeText Text:="There are " & _
      FontCount & " fonts used in the document, as follows:"
    Selection.TypeParagraph
    Selection.TypeParagraph
    For J = 1 To FontCount
        Selection.TypeText Text:=FontList(J)
        Selection.TypeParagraph
    Next J
End Sub

Obviously, the longer your document, the longer it will take the macro to finish. (I ran the macro on an 1,100 page document and it took approximately 46 minutes. On a 5 page document it took less than a minute.) When done, the macro creates a new document that contains a sorted list of the fonts used.

If you would like to know how to use the macros described on this page (or on any other page on the WordTips sites), I’ve prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

WordTips is your source for cost-effective Microsoft Word training.
(Microsoft Word is the most popular word processing software in the world.)
This tip (13313) applies to Microsoft Word 2007, 2010, and 2013. You can find a version of this tip for the older menu interface of Word here: Creating a Document Font List.

Author Bio

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. Learn more about Allen…

MORE FROM ALLEN

Space after a Table

Those familiar with styles are used to setting vertical spacing before or after paragraphs. You can get just the look you …

Discover More

Repeating a Pattern when Copying or Filling Cells

The fill tool can be a great help in copying patterns of information in a column. It isn’t so great, though, when the …

Discover More

Specifying How Clicking Works

Do you want to fundamentally change how Windows responds to mouse clicking? You can do so by following the steps outlined …

Discover More

Студворк — интернет-сервис помощи студентам

Доброй ночи, адепты)
Вы не раз меня выручали, уповаю на вашу помощь и теперь!

Скажем есть некий текст, набранный Times New Roman-ом, и среди него встречаются слова которые почему то решили быть набраны Arial-ом. (такой документик я прилепил к сообщению)

Надо бы чтобы Ариалы не отбивались от общего настроения и тоже стали Таймсами
Это легко лечится заменой, но хотелось бы делать это нажатием одной кнопки.

Однако, когда я записываю макрос, который должен повторить мои действия по замене всех Ариалов на Таймсы, то он выглядит следующим образом и не работает. В чем же дело? помогите пожалуйста (( желательно детсадовским языком, ибо я не программист.

Спасибо)

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Sub testing()
'
' testing Macros
'
'
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Понравилась статья? Поделить с друзьями:
  • Word all caps no caps lock
  • Word all about the bass
  • Word all about that bass
  • Word alive you are all i see
  • Word align to top