Vba word текст по центру

0 / 0 / 0

Регистрация: 29.12.2014

Сообщений: 4

1

16.12.2015, 01:56. Показов 11208. Ответов 5


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

Здравствуйте. нужна помощь в данном вопросе.
нужно в выбранном файле(пользователь сам выбирает файл) выровнять весь текст по центру, при этом что бы таблицы,заголовки и картинки оставались не тронутыми. Пробовал через стандартное выделение но там затрагивает все.



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

16.12.2015, 01:56

5

Ушел с CyberForum совсем!

873 / 182 / 25

Регистрация: 04.05.2011

Сообщений: 1,020

Записей в блоге: 110

16.12.2015, 07:24

2

могу посоветовать такой вариант
1. пройти по документу и считать в массив, какое выравнивание у каждой таблицы, заголовка, картинки
2. применить ко всему документу выравнивание по центру
3. пройти по таблицам, заголовкам, картинкам и вернуть им исходное выравнивание



0



Модератор

Эксперт MS Access

11341 / 4660 / 748

Регистрация: 07.08.2010

Сообщений: 13,497

Записей в блоге: 4

16.12.2015, 07:41

3

пройти по параграфам
—если не таблица(selection.information(wdwithintable)=false
—не заголовок(уровень не основной текст)
—длина текста в параграфе более 2
———то выровнять по центру

правда непонятно, что делать с маркированными и нумерованными списками и если заголовок выделен только жирностью, а не стилем или уровнем



1



FloyraitFai

0 / 0 / 0

Регистрация: 29.12.2014

Сообщений: 4

16.12.2015, 09:47

 [ТС]

4

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Sub CommandButton1_Click()
    FileName$ = GetFilePath()
    If FileName$ = "" Then Exit Sub
    MsgBox "Выбран файл: " & FileName$
End Sub
 
Function GetFilePath(Optional ByVal Title As String = "Выберите файл для обработки", _
                     Optional ByVal InitialPath As String = "c:", _
                     Optional ByVal FilterDescription As String = "Файлы счетов", _
                     Optional ByVal FilterExtention As String = "*.*") As String
    On Error Resume Next
    With Application.FileDialog(msoFileDialogOpen)
        .ButtonName = "Выбрать": .Title = Title:
        .InitialFileName = GetSetting(Application.Name, "GetFilePath", "folder", InitialPath)
        .Filters.Clear: .Filters.Add FilterDescription, FilterExtention
        If .Show <> -1 Then Exit Function
        GetFilePath = .SelectedItems(1)
        folder$ = Left(.SelectedItems(1), InStrRev(.SelectedItems(1), ""))
        SaveSetting Application.Name, "GetFilePath", "folder", folder$
    End With
End Function
 
Sub CommandButton2_Click()
Dim Path As String
Path = ThisDocument.Path
Dim oMyDoc As Word.Document
Set oMyDoc = Documents.Open(FileName$)
oMyDoc.Activate
Dim p As Paragraph
For Each p In ActiveDocument.Paragraphs
 If (Selection.Information(wdWithInTable) = False Or Selection.Information(wdPrimaryHeaderStory) = False) Then
   With ActiveDocument.Range.ParagraphFormat
    'Выравнивание
    Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft
End With
End If
Next
 
End Sub

Вот что накодил тоько что-то не работает=)



0



shanemac51

Модератор

Эксперт MS Access

11341 / 4660 / 748

Регистрация: 07.08.2010

Сообщений: 13,497

Записей в блоге: 4

16.12.2015, 10:44

5

ДОБАВИЛА ОТЛАДОК

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
''Option Explicit
Dim FileName$
Sub CommandButton1_Click()
    FileName$ = GetFilePath()
    If FileName$ = "" Then Exit Sub
    Debug.Print "Выбран файл: " & FileName$
    CommandButton2_Click
End Sub
 
Function GetFilePath(Optional ByVal Title As String = "Выберите файл для обработки", _
            Optional ByVal InitialPath As String = "c:", _
            Optional ByVal FilterDescription As String = "Файлы счетов", _
            Optional ByVal FilterExtention As String = "*.*") As String
    On Error Resume Next
    With Application.FileDialog(msoFileDialogOpen)
        .ButtonName = "Выбрать"
        .Title = Title:
        .InitialFileName = GetSetting(Application.Name, "GetFilePath", "folder", InitialPath)
        .Filters.Clear
        .Filters.Add FilterDescription, FilterExtention
        If .Show <> -1 Then
        Exit Function
        End If
        GetFilePath = .SelectedItems(1)
        Folder$ = Left(.SelectedItems(1), InStrRev(.SelectedItems(1), ""))
        SaveSetting Application.Name, "GetFilePath", "folder", Folder$
    End With
End Function
 
Sub CommandButton2_Click()
Dim Path As String
Path = ThisDocument.Path
Dim oMyDoc As Word.Document
Set oMyDoc = Documents.Open(FileName$)
oMyDoc.Activate
Dim p As Paragraph, J1, J2
Debug.Print Word.ActiveDocument.Name
For Each p In ActiveDocument.Paragraphs
p.Range.Select
'Or Selection.Information(wdPrimaryHeaderStory) = True
Debug.Print Selection.Information(wdPrimaryHeaderStory), p.Range.Text; " ";
 If (Selection.Information(wdWithInTable) = True) Then
Debug.Print "*";
 J1 = 1
 ElseIf Selection.Information(wdPrimaryHeaderStory) = True Then
 J1 = 2
 Debug.Print J2
 Else
  Debug.Print 3
 
   With p.Range.ParagraphFormat
    'Выравнивание
    .Alignment = wdAlignParagraphCenter
End With
End If
Next
'MsgBox "ok"
End Sub



0



KoGG

5590 / 1580 / 406

Регистрация: 23.12.2010

Сообщений: 2,366

Записей в блоге: 1

16.12.2015, 15:23

6

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Sub CommandButton2_Click()
    Dim FileName As String, oMyDoc As Word.Document
    FileName = GetFilePath
    If FileName$ = "" Then Exit Sub
    MsgBox "Выбран файл: " & FileName$
    Set oMyDoc = Documents.Open(FileName$)
    oMyDoc.Activate
    Dim P As Paragraph
    For Each P In ActiveDocument.Paragraphs
       If IsOrdinaryParagraph(P) Then P.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
    Next
End Sub
Function IsOrdinaryParagraph(Par As Paragraph) As Boolean
    Dim ParCharLen&, i&
    With Par.Range
        ParCharLen = Len(Trim$(.Text))
        If ParCharLen = 1 Then Exit Function            ' Пустая строка
        If .ListFormat.ListType > 0 Then Exit Function  ' Список
        If .Tables.Count > 0 Then Exit Function         ' Таблица
        If .InlineShapes.Count > 0 Then Exit Function   ' Рисунок
        If .OMaths.Count > 0 Then Exit Function         ' Формула
        If .Style.NameLocal Like "Заголовок*" Then Exit Function 'Заголовок
        Select Case .StoryType
            Case wdCommentsStory ' Комментарии.
                Exit Function
            Case wdEndnoteContinuationNoticeStory
                Exit Function
            Case wdEndnoteContinuationSeparatorStory
                Exit Function
            Case wdEndnoteSeparatorStory
                Exit Function
            Case wdEndnotesStory
                Exit Function
            Case wdEvenPagesFooterStory ' Нижний колонтитул
                Exit Function
            Case wdEvenPagesHeaderStory ' Верхний колонтитул
                Exit Function
            Case wdFirstPageFooterStory ' Нижний колонтитул 1-ой страницы раздела
                Exit Function
            Case wdFirstPageHeaderStory ' Верхний колонтитул 1-ой страницы раздела
                Exit Function
            Case wdFootnoteContinuationNoticeStory
                Exit Function
            Case wdFootnoteContinuationSeparatorStory
                Exit Function
            Case wdFootnoteSeparatorStory
                Exit Function
            Case wdFootnotesStory  'Текст сноски.
                Exit Function
            Case wdPrimaryFooterStory ' Нижний колонтитул
                Exit Function
            Case wdPrimaryHeaderStory ' Верхний колонтитул
                Exit Function
            Case wdTextFrameStory  'Текстовая рамка - полотно
                Exit Function
            Case wdMainTextStory ' Основной текст , только его и надо проверять
            Case Else
                Exit Function
        End Select
        If .Fields.Count > 0 Then
            For i = 1 To .Fields.Count
                Select Case .Fields(i).Type
                    Case wdFieldTOC: Exit Function            ' Содержание
                    Case wdFieldEmbed: Exit Function          ' Внедренный OLE объект
                    Case wdFieldIncludePicture: Exit Function ' Поле с рисунком
                    Case wdFieldBibliography: Exit Function   ' Поле - библиография
                End Select
            Next i
        End If
        If ParCharLen < 20 And (UCase$(.Text) Like "РИС*") Then Exit Function ' Нумерация рисунков
        If ParCharLen < 20 And (UCase$(.Text) Like "ДИА*") Then Exit Function ' Нумерация диаграмм
        If ParCharLen < 20 And (UCase$(.Text) Like "ТАБ*") Then Exit Function ' Нумерация таблиц
    End With
    IsOrdinaryParagraph = True
End Function



0



  • Добро пожаловать на Форум по VBA, Excel и Word.

  • Войти


  • Регистрация

 

Форум по VBA, Excel и Word

Почта для связи: Box1100@yandex.ru

14 апреля 2023, 20:34


Главное меню

Главное меню

  • Начало

  • Поиск

  • Форум по VBA, Excel и Word

  • Word

  • Макросы в Word

  • Word VBA Макросы. Как выровнять текст по центру ячейки?

Автор Посетитель 08.07.2021, 21 июля 2021, 16:12

Печать

Вниз
Страницы1

Действия пользователя


Посетитель 08.07.2021

  • Посетитель форума
  • Сообщения: 12
  • Записан

Word VBA Макросы. Как выровнять текст по центру ячейки?




21 июля 2021, 16:12


Как сделать так, чтобы текст был в ячейке не слева, а по центру?



Администратор

  • Administrator
  • Сообщения: 2,252
  • Записан

Re: Word VBA Макросы. Как выровнять текст по центру ячейки?

#1




21 июля 2021, 16:15


Этот макрос выравнивает текст по центру ячейки, внутри которой находится курсор.

Sub Макрос()
    Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
End Sub



Посетитель 08.07.2021

  • Посетитель форума
  • Сообщения: 12
  • Записан

Re: Word VBA Макросы. Как выровнять текст по центру ячейки?

#2




21 июля 2021, 16:19


спасибо


Печать

Вверх
Страницы1

Действия пользователя

  • Форум по VBA, Excel и Word

  • Word

  • Макросы в Word

  • Word VBA Макросы. Как выровнять текст по центру ячейки?

Действия пользователя

Печать

I have created a textbox in Word and can set various properties for it, such as position, text, text style, text horizontal alignment (left/right/center), color, and so on.

But I cannot find any settings to set the vertical alignment of text in the box to Top/Middle/Bottom. There’s a button for vertical alignment on the ribbon to set that property, but I can’t find it through the object inspector, through Intellisense, or through searching the net. I tried recording a macro, but the only line that showed up in the macro was the VBA line to select the textbox. Nothing else. :-(

The ribbon button is beside the «set text direction» option, but I couldn’t find VBA for that setting either. I also tried the Textframe2 property, but saw nothing in there for vertical alignment.

Here’s the code that sets the horizontal alignment of text. Also, I included the enum that I think I need to use. But I can’t find the property to accept a value from the enum.

   tbox.TextFrame.TextRange.ParagraphFormat.Alignment = wdAlignParagraphRight

WdVerticalAlignment enumeration (Word):
Name                 Value  Description
wdAlignVerticalBottom   3   Bottom vertical alignment.
wdAlignVerticalCenter   1   Center vertical alignment.
wdAlignVerticalJustify  2   Justified vertical alignment.
wdAlignVerticalTop      0   Top vertical alignment.

Does anyone know the syntax for the property that I need to set to vertically align text inside a textbox shape? Thank you

  • Remove From My Forums
  • Question

  • Feeling like a complete idiot and not sure if I’m posting to the right place but this should be the last of 3 posts. I’m creating an MS Word table. Inserting text OK. Now that the text is inserted I want to set it to be aligned to the bottom of the cell
    that it’s in.

    However this is not working and the closest thing I can find.

    In fact I’m finding very little about aligning text inside a cell of an MS Word table with VBA at all. I’ve actually tried four variations of this with no luck.

    WordObj.ActiveDocument.Tables(4).Cell(Row:=N, Column:=1).Range.ParagraphFormat.Alignment = wdAlignVerticalBottom

Sub CommandButton2_Click()
    Dim FileName As String, oMyDoc As Word.Document
    FileName = GetFilePath
    If FileName$ = "" Then Exit Sub
    MsgBox "Выбран файл: " & FileName$
    Set oMyDoc = Documents.Open(FileName$)
    oMyDoc.Activate
    Dim P As Paragraph
    For Each P In ActiveDocument.Paragraphs
       If IsOrdinaryParagraph(P) Then P.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
    Next
End Sub
Function IsOrdinaryParagraph(Par As Paragraph) As Boolean
    Dim ParCharLen&, i&
    With Par.Range
        ParCharLen = Len(Trim$(.Text))
        If ParCharLen = 1 Then Exit Function            ' Пустая строка
        If .ListFormat.ListType > 0 Then Exit Function  ' Список
        If .Tables.Count > 0 Then Exit Function         ' Таблица
        If .InlineShapes.Count > 0 Then Exit Function   ' Рисунок
        If .OMaths.Count > 0 Then Exit Function         ' Формула
        If .Style.NameLocal Like "Заголовок*" Then Exit Function 'Заголовок
        Select Case .StoryType
            Case wdCommentsStory ' Комментарии.
                Exit Function
            Case wdEndnoteContinuationNoticeStory
                Exit Function
            Case wdEndnoteContinuationSeparatorStory
                Exit Function
            Case wdEndnoteSeparatorStory
                Exit Function
            Case wdEndnotesStory
                Exit Function
            Case wdEvenPagesFooterStory ' Нижний колонтитул
                Exit Function
            Case wdEvenPagesHeaderStory ' Верхний колонтитул
                Exit Function
            Case wdFirstPageFooterStory ' Нижний колонтитул 1-ой страницы раздела
                Exit Function
            Case wdFirstPageHeaderStory ' Верхний колонтитул 1-ой страницы раздела
                Exit Function
            Case wdFootnoteContinuationNoticeStory
                Exit Function
            Case wdFootnoteContinuationSeparatorStory
                Exit Function
            Case wdFootnoteSeparatorStory
                Exit Function
            Case wdFootnotesStory  'Текст сноски.
                Exit Function
            Case wdPrimaryFooterStory ' Нижний колонтитул
                Exit Function
            Case wdPrimaryHeaderStory ' Верхний колонтитул
                Exit Function
            Case wdTextFrameStory  'Текстовая рамка - полотно
                Exit Function
            Case wdMainTextStory ' Основной текст , только его и надо проверять
            Case Else
                Exit Function
        End Select
        If .Fields.Count > 0 Then
            For i = 1 To .Fields.Count
                Select Case .Fields(i).Type
                    Case wdFieldTOC: Exit Function            ' Содержание
                    Case wdFieldEmbed: Exit Function          ' Внедренный OLE объект
                    Case wdFieldIncludePicture: Exit Function ' Поле с рисунком
                    Case wdFieldBibliography: Exit Function   ' Поле - библиография
                End Select
            Next i
        End If
        If ParCharLen < 20 And (UCase$(.Text) Like "РИС*") Then Exit Function ' Нумерация рисунков
        If ParCharLen < 20 And (UCase$(.Text) Like "ДИА*") Then Exit Function ' Нумерация диаграмм
        If ParCharLen < 20 And (UCase$(.Text) Like "ТАБ*") Then Exit Function ' Нумерация таблиц
    End With
    IsOrdinaryParagraph = True
End Function

Понравилась статья? Поделить с друзьями:
  • Vba word текст закладки
  • Vba word текст в ячейке таблицы
  • Vba word таблица цвет ячейки
  • Vba word таблица в таблице
  • Vba word таблица range