Vba excel выравнивание по центру

Выравнивание текста и других значений в ячейке по горизонтали и вертикали из кода VBA Excel. Свойства HorizontalAlignment и VerticalAlignment. Примеры.

Выравнивание по горизонтали

Для выравнивания текста в ячейках рабочего листа по горизонтали в VBA Excel используется свойство HorizontalAlignment объекта Range. Оно может принимать следующие значения:

Выравнивание Константа Значение
По левому краю xlLeft -4131
По центру xlCenter -4108
По правому краю xlRight -4152
Равномерно по ширине xlJustify -4130
По умолчанию xlGeneral 1

Константу использовать удобнее, так как ее можно выбрать из подсказок и легче запомнить. Но и присвоение свойству HorizontalAlignment непосредственно числового значения константы будет работать точно так же.

Пример 1
Заполним три первые ячейки листа Excel текстом, соответствующим предполагаемому выравниванию. Затем применим к ним выравнивание по горизонтали, а в ячейках ниже выведем соответствующие значения констант.

Sub Primer1()

‘Заполняем ячейки текстом

   Range(«A1») = «Левая сторона»

   Range(«B1») = «Центр ячейки»

   Range(«C1») = «Правая сторона»

‘Применяем горизонтальное выравнивание

   Range(«A1»).HorizontalAlignment = xlLeft

   Range(«B1»).HorizontalAlignment = xlCenter

   Range(«C1»).HorizontalAlignment = xlRight

‘Выводим значения констант

   Range(«A2») = «xlLeft  =  « & xlLeft

   Range(«B2») = «xlCenter  =  « & xlCenter

   Range(«C2») = «xlRight  =  « & xlRight

End Sub

Выравнивание по вертикали

Для выравнивания текста в ячейках рабочего листа по вертикали в VBA Excel используется свойство VerticalAlignment объекта Range. Оно может принимать следующие значения:

Выравнивание Константа Значение
По верхнему краю xlTop -4160
По центру xlCenter -4108
По нижнему краю xlBottom -4107
Равномерно по высоте xlJustify -4130

Точно так же, как и по горизонтали, при выравнивании по вертикали свойству VerticalAlignment можно присваивать как значение в виде константы, так и непосредственно ее числовое значение.

Пример 2
Заполним три первые ячейки третьей строки листа Excel текстом, соответствующим предполагаемому выравниванию. Затем применим к ним выравнивание по вертикали, а в ячейках ниже выведем соответствующие значения констант.

Sub Primer2()

‘Заполняем ячейки текстом

   Range(«A3») = «Верх»

   Range(«B3») = «Центр»

   Range(«C3») = «Низ»

‘Применяем вертикальное выравнивание

   Range(«A3»).VerticalAlignment = xlTop

   Range(«B3»).VerticalAlignment = xlCenter

   Range(«C3»).VerticalAlignment = xlBottom

‘Выводим значения констант

   Range(«A4») = «xlTop  =  « & xlTop

   Range(«B4») = «xlCenter  =  « & xlCenter

   Range(«C4») = «xlBottom  =  « & xlBottom

End Sub

Двойное выравнивание

В следующем примере рассмотрим выравнивание из кода VBA одновременно по горизонтали и вертикали. Причем, применим выравнивание ко всем ячейкам рабочего листа Excel, которые были задействованы в предыдущих примерах.

Пример 3
Записываем в ячейки диапазона «A1:C4» текст «Всё по центру», применяем горизонтальное и вертикальное выравнивание по центру для всего диапазона.

Sub Primer3()

   With Range(«A1:C4»)

      .Value = «Всё по центру»

      .HorizontalAlignment = 4108

      .VerticalAlignment = xlCenter

   End With

End Sub

Обратите внимание, что выравнивание текста применяется как при использовании константы, так и соответствующего ей числового значения.


Return to VBA Code Examples

This tutorial will demonstrate how to use VBA to Center Text in Cells both Horizontally and Vertically.

We can use the Alignment group in the Home Ribbon in Excel to center text both horizontally and vertically in a cell. If we are writing a macro to format text, we can re-create this functionality using VBA Code.

Center Text Horizontally

To Center Text horizontally in a single cell, we can use the following code:

Sub CenterText()
 ActiveCell.HorizontalAlignment = xlCenter
End Sub

Alternatively, to center text horizontally in each cell of a selected range of cells, we can use the Selection object and do the following:

Sub CenterText()
 Selection.HorizontalAlignment = xlCenter
End Sub

We can also change the alignment to right or left using the xlLeft and xlRight constants.

To right align the text in a cell, we can therefore use the following code:

Sub RightAlignText() 
 ActiveCell.HorizontalAlignment = xlRight
End Sub

Center Text Vertically

Centering the text vertically is much the same as horizontally.

Sub CenterTextVertical()
 ActiveCell.VerticalAlignment = xlCenter
End Sub

As is centering text vertically across a selection:

Sub CenterTextVertically() 
 Selection.VerticalAlignment = xlCenter 
End Sub

We can also change the text to the Top or Bottom of a cell or selection using the xlTop or xlBottom constants.

Sub TopAlignVertically() 
 ActiveCell.VerticalAlignment = xlTop
End Sub

Center Text Horizontally and Vertically at the Same Time

If we want to center the text both Horizontally and Vertically at the same time, there are a couple of ways we can do so.

Sub CenterBoth()
 ActiveCell.HorizontalAlignment = xlCenter
 ActiveCell.VerticalAlignment = xlCenter
End Sub

To cut down on repeating code, we can use a With and End With Statement.

Sub CenterBoth2()
  With Selection
   .HorizontalAlignment = xlCenter
   .VerticalAlignment = xlCenter
  End With
End Sub

The code above will apply to all the cells in Excel that are selected at the time.

CenterText With

Using With and End With is very effective when we have a lot of formatting to do within the selection, such as merging cells or changing orientation.

Sub MergeAndCenter()
  With Selection
   .HorizontalAlignment = xlCenter
   .VerticalAlignment = xlBottom
   .Orientation = -36
   .MergeCells = True
  End With
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Excel VBA, Horizontal Alignment

Aug 11, 2015 in Excel

In this article I will explain the different horizontal alignment formattings applicable to cells and range. I have also provided the VBA code required to apply them.

For examples using horizontal alignment in VBA code please see:

  • Excel VBA, Set Horizontal Alignment, (Sample Code)
  • Excel VBA, Get Horizontal Alignment (Sample Code)

Jump To:

  • Left (Indent), xlLeft
  • Center, xlCenter
  • Right (Indent), xlRight
  • Fill, xlFill
  • Justify, xlJustify
  • Center Across Selection, xlCenterAcrossSelection
  • Distributed (Indent), xlDistributed
  • General, xlGeneral
  • Indent, IndentLevel


Left (Indent), xlLeft:

The following code will left align the text in cell “A1”:

Range("A1").HorizontalAlignment = xlLeft

Result:

Left (Indent) XlLeft


Center, xlCenter:

The following code will apply the horizontal center alignment to the text in cell “A1”:

Range("A1").HorizontalAlignment = xlCenter

Result:

Center, XLCenter


Right (Indent), xlRight:

The following code will right align the text in cell “A1”:

Range("A1").HorizontalAlignment = xlRight

Result:

Right (Indent), xlRight, Excel VBA


Fill, xlFill:

The following code will fill the cell in “A1” with the text in it:

Range("A1").HorizontalAlignment = xlFill

Result:

Fill, xlFill, Excel VBA


Justify, xlJustify:

The following code will apply the horizontal justify formatting to the text in cell “A1”. Note that the justify property will only be apparent when you have multiple lines of text in a cell and the wrap property is on:

Range("A1").HorizontalAlignment = xlJustify

Result:

Justify, xlJustify, Excel VBA


Center Across Selection, xlCenterAcrossSelection:

The following code centers the text in cell “A1” among the cells A1~I1. This is a good way of centering a text over multiple columns without merging the cells:

Range("A1:M1").Select
Selection.HorizontalAlignment = xlCenterAcrossSelection

Before:

Center Across Selection,xlCenterAcrossSelection , Before Excel VBA

After:

Center Across Selection,xlCenterAcrossSelection , After Excel VBA


Distributed, xlDistributed:

The following command applies the distributed (indent) formatting to cell “A1”. This formatting creates spaces between the words so that the entire horizontal spacing in that cell is filled:

Range("A1").HorizontalAlignment = xlDistributed

Before:

Distributed, xLDistributed, Excel VBA

After:

Distributed, xLDistributed, After Excel VBA


General, xlGeneral:

The following command applies the general horizontal formatting to cell “A1”. This formatting causes text to be left aligned and numbers to be right aligned:

Range("A1").HorizontalAlignment = xlGeneral

Result:

General, xLGeneral, Excel VBA


Indent, IndentLevel:

The 3 formattings left aligned, right aligned and distributed accept an indentation level. The code below applies an indentation to the cells A1, A2 and A3:

Range("A1").IndentLevel= 1

Before:

Indent, IndentLevel, Before, Excel VBA

After:
Indent, IndentLevel, After, Excel VBA
See also:

  • Excel VBA Formatting Cells and Ranges Using the Macro Recorder
  • VBA Excel, Alignment
  • Excel VBA, Set Horizontal Alignment, (Sample Code)
  • Excel VBA, Get Horizontal Alignment (Sample Code)

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

Содержание

  • Центрировать текст по горизонтали
  • Центрировать текст по вертикали
  • Центрировать текст по горизонтали и вертикали одновременно

В этом руководстве будет показано, как использовать VBA для центрирования текста в ячейке как по горизонтали, так и по вертикали.

Мы можем использовать группу «Выравнивание» на главной ленте в Excel для центрирования текста как по горизонтали, так и по вертикали в ячейке. Если мы пишем макрос для форматирования текста, мы можем воссоздать эту функциональность с помощью кода VBA.

Центрировать текст по горизонтали

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

123 Подцентртекст ()ActiveCell.HorizontalAlignment = xlCenterКонец подписки

В качестве альтернативы, чтобы центрировать текст по горизонтали в каждой ячейке выбранного диапазона ячеек, мы можем использовать объект Selection и сделать следующее:

123 Подцентртекст ()Selection.HorizontalAlignment = xlCenterКонец подписки

Мы также можем изменить выравнивание вправо или влево, используя xlLeft а также xlRight константы.

Чтобы выровнять текст в ячейке по правому краю, мы можем использовать следующий код:

123 Sub RightAlignText ()ActiveCell.HorizontalAlignment = xlRightКонец подписки

Центрировать текст по вертикали

Центрирование текста по вертикали почти такое же, как и по горизонтали.

123 Sub CenterTextVertical ()ActiveCell.VerticalAlignment = xlCenterКонец подписки

Как и центрирование текста по вертикали по выделенному фрагменту:

123 ПодцентрТекстВертикально ()Selection.VerticalAlignment = xlCenterКонец подписки

Мы также можем изменить текст на верхнюю или нижнюю часть ячейки или выделения, используя xlTop или xlBottom константы.

123 Sub TopAlignVertical ()ActiveCell.VerticalAlignment = xlTopКонец подписки

Центрировать текст по горизонтали и вертикали одновременно

Если мы хотим центрировать текст одновременно по горизонтали и вертикали, есть несколько способов сделать это.

1234 Sub CenterBoth ()ActiveCell.HorizontalAlignment = xlCenterActiveCell.VerticalAlignment = xlCenterКонец подписки

В качестве альтернативы, чтобы сократить повторяющийся код, мы можем использовать инструкции With и End With.

123456 ПодцентрBoth2 ()С выделением.HorizontalAlignment = xlCenter.VerticalAlignment = xlCenterКонец сКонец подписки

Приведенный выше код будет применяться ко всем ячейкам Excel, выбранным в данный момент.

Использование With и End With очень эффективно, когда у нас есть много форматирования внутри выделения, например, слияние ячеек или изменение ориентации.

12345678 Sub MergeAndCenter ()С выделением.HorizontalAlignment = xlCenter.VerticalAlignment = xlBottomОриентация = -36.MergeCells = ИстинаКонец сКонец подписки

Вы поможете развитию сайта, поделившись страницей с друзьями

Private Sub Workbook_NewSheet(ByVal Sh As Object)
    With Sh
        With .Range("a1:w1")
            .Value = Array("W/O", "CUSTOMER", "DETAILS", "CUST PART NO", "STATUS", _
                           "NOTES", "DEPARTMENT", "DATE", "CUST ORDER NO", "DEL NO", _
                           "QTY", "SALE PRICE", "CARRIAGE OUT", "TOTAL SALES", _
                           "INT CODE", "SUPPLIER", "COST PRICE", "CARRIAGE IN", _
                           "TOTAL HRS", "LABOUR COST", "TOTAL COST", _
                           "GROSS PROFIT", "GROSS PROFIT")

            .ColumnWidth = Array(9.71, 24.29, 47.71, 16, 13.57, 24.71, 15.43, _
                                 8.57, 16.29, 8.41, 7.71, 12.43, 15, 13.71, 12.14, _
                                 23.29, 13.14, 13.71, 11.29, 11.29, 13, 14.86, 14.86)

            .HorizontalAlignment = xlCenter
            With .Font
                .Size = 8
                .Bold = True
            End With
        End With
    End With
End Sub

In Excel 2007, I inserted an ActiveX label onto my worksheet. I right-clicked on it and viewed Properties and managed to change the TextAlign property to 2 (frmTextAlignCenter).

This aligns the label caption’s text to the center of the label (horizontally), but the text remains at the TOP of the label. How do I center the caption’s text VERTICALLY so that it is in the smack middle of the label?

I’ve searched «vertical alignment» in SO but nothing comes up for how to do this for an Excel label’s caption.

bad_coder's user avatar

bad_coder

10.8k20 gold badges44 silver badges68 bronze badges

asked Jul 28, 2011 at 12:41

MrPatterns's user avatar

There is a trick to do it with a single label.
Add an transparent gif image of 1×1 pixel (here) and set the PictureAlignment property to PicturePositionLeftCenter.

Greedo's user avatar

Greedo

4,7892 gold badges29 silver badges76 bronze badges

answered Sep 30, 2014 at 23:11

Larv's user avatar

LarvLarv

3113 silver badges2 bronze badges

5

There’s no way to do it directly. This post has a clever way to accomplish it, though. Make 2 boxes, with the inner one autosized around the text, and position that inner box at the midpoint of the outer box.

answered Jul 28, 2011 at 12:49

jonsca's user avatar

jonscajonsca

10.2k26 gold badges56 silver badges62 bronze badges

1

I just tried the approach outlined in the top voted answer and it worked perfectly. To add a little to the approach though — if you have many labels for example, I did the following:

  1. Add a picture control somewhere on the userform (anywhere doesn’t matter). Change the control’s properties to the following:
Property Value
Name GIF
Picture (set to be the 1×1 transparent gif picture [link])
Visible False
  1. Now for each of the Label controls which you want to receive the special alignment change the tag property:
Property Value
Tag "LabelAlignmentTheme"
  1. Finally add the following code to UserForm_Initialize
Private Sub UserForm_Initialize()
    'Apply the fix in https://stackoverflow.com/questions/6859127/how-do-i-vertically-center-the-text-in-an-excel-labels-caption
    'To all labels with the matching Tag
    Dim ctrl As MSForms.control
    For Each ctrl In Me.controls
        If TypeOf ctrl Is MSForms.label And ctrl.Tag = "LabelAlignmentTheme" Then
            Dim label As MSForms.label
            Set label = ctrl
            Set label.Picture = Me.GIF.Picture 'read the picture from the picture control
            label.PicturePosition = fmPicturePositionLeftCenter
        End If
    Next
End Sub

I like this use of Tag, it feels like a css style. Obviously you can skip the check for the tag (remove the second half of the And statement) and align absolutely everything but I think this is a more realistic scenario where you only want some aligned.

By storing the image in a shared hidden picture somewhere in the form, it is embedded in the file.

answered Feb 12, 2022 at 18:20

Greedo's user avatar

GreedoGreedo

4,7892 gold badges29 silver badges76 bronze badges

1

You will have to use 2 Labels.

For Example, Call them LabelBack, LabelFront. The LabelFront should be set to Opaque and No-Border Make the height of LabelFront smaller than that of LabelBack and put it over it more or less.

Then add the following code:

LabelFront.Top = (LabelBack.Top + (LabelBack.Height - LabelFront.Height) / 2) - 1

Notice, I subtracted 1 to compensate the 1 extra pixel within the LabelFront.

Steve Campbell's user avatar

answered Jun 18, 2016 at 23:08

YosiN's user avatar

YosiNYosiN

624 bronze badges

This look like (in class): author TRUNG SON

Public Enum VERTYCIAL_ALIGNMENTS
    ALIGN_TOP = 0
    ALIGN_MIDDLE = 1
    ALIGN_BOTTOM = 2
End Enum

Public Enum HORIZONTAL_ALIGNMENTS
    ALIGN_LEFT = 0
    ALIGN_CENTER = 1
    ALIGN_RIGHT = 2
End Enum

Public Enum BACK_STYLES
    TRANSPARENT = 0
    OPAQUE = 1
End Enum

'khai bao cac thuoc tinh can thay doi
Private text_ As String
Private top_ As Double
Private left_ As Double
Private width_ As Double
Private height_ As Double
Private font_name As String
Private font_size As Double
Private horizontal_align As Double
Private vertical_align As Double
Private font_bold As Boolean
Private font_italic As Boolean
Private back_style As Byte
Private back_color As Long
Private fore_color As Long
Private border_color As Long
Private align_hor_type As Double
Private align_ver_type As Double
'------------------------------------

'khai bao cac controls
Private labelText As MSForms.label
Private labelBackground As MSForms.label
'---------------------

'ham khoi tao cua class
Private Sub Class_Initialize()
End Sub

Public Sub Add(Parent As Object) 'them control vao control cha, frame hoac userform (ve len mac dinh)
    Set labelBackground = Parent.Controls.Add("Forms.Label.1")
    Set labelText = Parent.Controls.Add("Forms.Label.1")
    
    'khoi tao gia tri cho bien
    text_ = ""
    top_ = 0
    left_ = 0
    width_ = 50
    height_ = 20
    font_name = "Times New Roman"
    font_size = 12
    horizontal_align = SetTextHorizaontal(HORIZONTAL_ALIGNMENTS.ALIGN_CENTER)
    vertical_align = SetTextVertical(VERTYCIAL_ALIGNMENTS.ALIGN_MIDDLE)
    font_bold = False
    font_italic = False
    back_style = fmBackStyleTransparent
    back_color = vbWhite
    fore_color = vbBlack
    border_color = vbBlack
    '-------------------------
    
    'khoi tao gia tri cho label background
    labelBackground.Top = top_
    labelBackground.Left = left_
    labelBackground.Width = width_
    labelBackground.Height = height_
    labelBackground.BorderStyle = fmBorderStyleSingle
    labelBackground.BorderColor = border_color
    labelBackground.BackStyle = back_style
    labelBackground.BackColor = back_color
    '--------------------------------------
    
    'khoi tao gia tri cho label text
    labelText.Caption = text_
    labelText.font.Name = font_name
    labelText.font.Size = font_size
    labelText.font.Bold = font_bold
    labelText.font.Italic = font_italic
    labelText.WordWrap = False
    labelText.AutoSize = True
    labelText.Top = vertical_align
    labelText.Left = horizontal_align
    labelText.ForeColor = fore_color
    labelText.BackStyle = 0
End Sub

Sub Draw() 'Customize label, ve len frame hoac userform sau khi co thay doi cac thuoc tinh
    'gan gia tri cho label background
    labelBackground.Top = top_
    labelBackground.Left = left_
    labelBackground.Width = width_
    labelBackground.Height = height_
    labelBackground.BorderStyle = fmBorderStyleSingle
    labelBackground.BorderColor = border_color
    labelBackground.BackStyle = back_style
    labelBackground.BackColor = back_color
    '--------------------------------------
    
    'gan gia tri cho label text
    labelText.Caption = text_
    labelText.font.Name = font_name
    labelText.font.Size = font_size
    labelText.font.Bold = font_bold
    labelText.font.Italic = font_italic
    If align_ver_type = VERTYCIAL_ALIGNMENTS.ALIGN_TOP Then
        vertical_align = SetTextVertical(VERTYCIAL_ALIGNMENTS.ALIGN_TOP)
    ElseIf align_ver_type = VERTYCIAL_ALIGNMENTS.ALIGN_MIDDLE Then
        vertical_align = SetTextVertical(VERTYCIAL_ALIGNMENTS.ALIGN_MIDDLE)
    Else
        vertical_align = SetTextVertical(VERTYCIAL_ALIGNMENTS.ALIGN_BOTTOM)
    End If
    labelText.Top = vertical_align
    If align_hor_type = HORIZONTAL_ALIGNMENTS.ALIGN_LEFT Then
        horizontal_align = SetTextHorizaontal(HORIZONTAL_ALIGNMENTS.ALIGN_LEFT)
    ElseIf align_hor_type = HORIZONTAL_ALIGNMENTS.ALIGN_CENTER Then
        horizontal_align = SetTextHorizaontal(HORIZONTAL_ALIGNMENTS.ALIGN_CENTER)
    Else
        horizontal_align = SetTextHorizaontal(HORIZONTAL_ALIGNMENTS.ALIGN_RIGHT)
    End If
    labelText.Left = horizontal_align
    labelText.ForeColor = fore_color
    labelText.BackStyle = 0
End Sub

'ham huy cua class
Private Sub Class_Terminate()
    Clear
End Sub

'cai dat cho cac thuoctinh cua class (begin)
Public Property Get Text() As String
    Text = text_
End Property

Public Property Let Text(ByVal Caption As String)
    text_ = Caption
End Property

Public Property Get Top() As Double
    Top = top_
End Property

Public Property Let Top(ByVal Position As Double)
    top_ = Position
End Property

Public Property Get Left() As Double
    Left = left_
End Property

Public Property Let Left(ByVal Position As Double)
    left_ = Position
End Property

Public Property Get Width() As Double
    Width = width_
End Property

Public Property Let Width(ByVal Dimension As Double)
    width_ = Dimension
End Property

Public Property Get Height() As Double
    Height = height_
End Property

Public Property Let Height(ByVal Dimension As Double)
    If Dimension <= labelText.Height + 6 Then
        height_ = labelText.Height + 6
        labelBackground.Height = height_
    Else
        height_ = Dimension
    End If
End Property

Public Property Let FontName(ByVal Style As String)
    font_name = Style
End Property

Public Property Let FontSize(ByVal Size As Double)
    font_size = Size
End Property

Public Property Let Horizontal_Alignment(ByVal Align As Double)
    horizontal_align = SetTextHorizaontal(Align)
End Property

Public Property Let Vertical_Alignment(ByVal Align As Double)
    vertical_align = SetTextVertical(Align)
End Property

Public Property Let FontBold(ByVal Bold As Boolean)
    font_bold = Bold
End Property

Public Property Let FontItalic(ByVal Italic As Boolean)
    font_italic = Italic
End Property

Public Property Let BackStyle(ByVal Style As Byte)
    If Style = BACK_STYLES.OPAQUE Then
        back_style = fmBackStyleOpaque
    Else
        back_style = fmBackStyleTransparent
    End If
End Property

Public Property Let BackColor(ByVal Color As Long)
    back_color = Color
End Property

Public Property Let ForeColor(ByVal Color As Long)
    fore_color = Color
End Property

Public Property Let BorderColor(ByVal Color As Long)
    border_color = Color
End Property
'-----------------------------------------------(end)

'cac ham xu ly khac
Private Function SetTextHorizaontal(Align As Double) As Double
    On Error Resume Next
    align_hor_type = Align
    
    If Align = HORIZONTAL_ALIGNMENTS.ALIGN_LEFT Then
        labelText.TextAlign = fmTextAlignLeft
        SetTextHorizaontal = left_ + 3
    ElseIf Align = HORIZONTAL_ALIGNMENTS.ALIGN_CENTER Then
        labelText.TextAlign = fmTextAlignCenter
        SetTextHorizaontal = left_ + (width_ - labelText.Width) / 2
    Else
        labelText.TextAlign = fmTextAlignRight
        SetTextHorizaontal = left_ + labelBackground.Width - labelText.Width - 3
    End If
End Function

Private Function SetTextVertical(Align As Double) As Double
    On Error Resume Next
    align_ver_type = Align
    
    If Align = VERTYCIAL_ALIGNMENTS.ALIGN_TOP Then
        SetTextVertical = top_ + 3 'cn top, cach top 3 don vi
    ElseIf Align = VERTYCIAL_ALIGNMENTS.ALIGN_MIDDLE Then
        SetTextVertical = top_ + (height_ - labelText.Height) / 2
    Else
        SetTextVertical = top_ + (height_ - labelText.Height) - 3
    End If
End Function

Public Sub Clear()
    Set labelBackground = Nothing
    Set labelText = Nothing
End Sub
'--------------------------------------------------

ter code here

answered May 11, 2022 at 4:00

Vũ Trung Sơn's user avatar

This look like (in module): author TRUNG SON

Public Enum VERTYCIAL_ALIGNMENT
    TOP = -1
    MIDDLE = 0
    BOTTOM = 1
End Enum

Public Enum BACK_STYLE
    OPAQUE = 1
    TRANSPARENT = 0
End Enum

Function CreateCenterText(CtlParent As Object, _
                        text As String, _
                        TOP As Double, _
                        Left As Double, _
                        Width As Double, _
                        Height As Double, _
                        Optional text_Align_Type As Integer = VERTYCIAL_ALIGNMENT.MIDDLE, _
                        Optional fontName As String = "Times New Roman", _
                        Optional fontSize As Double = 12, _
                        Optional fontBold As Boolean = False, _
                        Optional fontItalic As Boolean = False, _
                        Optional foreColor As Long = vbBlack, _
                        Optional backColor As Long = vbWhite, _
                        Optional backStyle As Long = BACK_STYLE.TRANSPARENT, _
                        Optional BorderColor As Long = vbBlack) As MSForms.label 'Customize label
    Dim lblBG As MSForms.label
    Dim lblText As MSForms.label
    
    Set lblBG = CtlParent.controls.Add("Forms.Label.1")
    Set lblText = CtlParent.controls.Add("Forms.Label.1")
    
    lblBG.TOP = TOP
    lblBG.Left = Left
    lblBG.Width = Width
    lblBG.Height = Height
    lblBG.TextAlign = 2
    lblBG.BorderStyle = fmBorderStyleSingle
    lblBG.BorderColor = BorderColor
    If backStyle = BACK_STYLE.OPAQUE Then
        lblBG.backStyle = fmBackStyleOpaque
    Else
        lblBG.backStyle = fmBackStyleTransparent
    End If
    lblBG.backColor = backColor
    
    lblText.Width = 500
    lblText.Height = 50
    lblText.caption = text
    lblText.font.Name = fontName
    lblText.font.SIZE = fontSize
    lblText.font.Bold = fontBold
    lblText.font.Italic = fontItalic
    lblText.foreColor = foreColor
    lblText.AutoSize = True
    Dim align As Double
    If text_Align_Type = VERTYCIAL_ALIGNMENT.TOP Then
        align = -((Height - lblText.Height) / 2) + 3 ''=TOP + 3
    ElseIf text_Align_Type = VERTYCIAL_ALIGNMENT.MIDDLE Then
        align = 0 ''=TOP + ((Height - lblText.Height) / 2)
    Else
        align = (Height - lblText.Height) / 2 - 3 ''=TOP + HEIGHT - lblText.Height
    End If
    lblText.TOP = TOP + ((Height - lblText.Height) / 2) + align
    lblText.Left = Left + (Width - lblText.Width) / 2
    lblText.TextAlign = 2
    lblText.WordWrap = False
    lblText.backStyle = 0
    
    Set CreateCenterText = lblBG
    
    Set lblBG = Nothing
    Set lblText = Nothing
End Function

9 / 9 / 1

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

Сообщений: 174

1

Как сделать выравнивание текста в ячейке

16.02.2012, 21:05. Показов 52454. Ответов 8


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

Мпа, добрый вечер!

Скажите, пожалуйста, как сделать выравнивание текста в ячейке средствами VBA? Какое свойство за это отвечает?

Заранее спасибо за ответ!



0



Watcher_1

356 / 162 / 27

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

Сообщений: 350

16.02.2012, 21:23

2

Visual Basic
1
2
3
Range("A1").HorizontalAlignment = xlLeft 'лево
Range("A1").HorizontalAlignment = xlCenter ' центр
Range("A1").HorizontalAlignment = xlRight ' право



2



Sasha_Smirnov

5561 / 1367 / 150

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

Сообщений: 4,107

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

16.02.2012, 21:24

3

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Sub Макрос1()
'
' Макрос1 Макрос
'
    Range("C5").Select 'выделенная ячейка таблицы Excel (с текстом)
'
    With Selection
        .HorizontalAlignment = xlCenter     'текст по центру
        .VerticalAlignment = xlBottom       'выровнен по вертикали вниз
    End With
    
    With Selection
        .HorizontalAlignment = xlLeft       'текст влево (так по умолчанию)
    End With
    
    With Selection
        .HorizontalAlignment = xlRight       'текст вправо
    End With
End Sub

А знаете как я сделал… Записал макрос и посмотрел по Alt-F11. Лишнее убрал.

А теперь таким же макаром — для ворда.

Подсказка: дежим зажатой клавишу Ctrl и жмём буквы: У (она же E) (по центру), R (вправо), L (влево).

А вот и

Visual Basic
1
2
3
4
5
Sub Макрос1()
    Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter    'по центру
    Selection.ParagraphFormat.Alignment = wdAlignParagraphRight     'вправо
    Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft      'догадайтесь сами
End Sub



2



9 / 9 / 1

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

Сообщений: 174

16.02.2012, 21:27

 [ТС]

4

Ура, спасибо!!!

Sasha_Smirnov, Слушайте, Вы гений!!! Молодец, отличная идея… Супер!



1



5561 / 1367 / 150

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

Сообщений: 4,107

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

17.02.2012, 00:23

5

Особо «гениален» глагол дежим… этакое дежавю.

Вообще-то я догадывался, что делаю «открытие Америки», но способ совершенно естественный.



1



avenger24

1 / 1 / 0

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

Сообщений: 84

14.04.2016, 12:33

6

Sasha_Smirnov, а не подскажешь как выровнить в Wordе по вертикали по центру ?

Visual Basic
1
2
3
4
5
Sub Макрос1()
    Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter    'по центру
    Selection.ParagraphFormat.Alignment = wdAlignParagraphRight     'вправо
    Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft      'догадайтесь сами
End Sub



0



Shersh

Заблокирован

14.04.2016, 12:59

7

Visual Basic
1
Selection.Cells.VerticalAlignment = wdCellAlignVerticalCenter

?



0



0 / 0 / 0

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

Сообщений: 212

25.05.2016, 09:17

8

а если надо по горизонтали, в cell.horizontalAligment нету



0



Shersh

Заблокирован

25.05.2016, 09:23

9

Цитата
Сообщение от ramzes2012
Посмотреть сообщение

cell.horizontalAligment нету

А такое может есть —
cellS.HorizontalAligNment
?



0



How can I align(center) my cell values for my below code?

For x = 0 To EleXML.ChildNodes.Length - 1    
      Range("A10").offset(x,0) = EleXML.ChildNodes.Item(x).getAttribute("aa")
      Range("A10").offset(x,0) = EleXML.ChildNodes.Item(x).getAttribute("bb")
      Range("A10").offset(x,0) = EleXML.ChildNodes.Item(x).getAttribute("cc")
Next x

Please help,thanks in advance.

Community's user avatar

asked May 29, 2013 at 12:24

user2144293's user avatar

0

Is it what you are looking for ?

s = 1
For x = 0 To EleXML.ChildNodes.Length - 1
    Range("A10").Offset(s, 0) = EleXML.ChildNodes.Item(x).getAttribute("aa")
    Range("A10").Offset(s + 1, 0) = EleXML.ChildNodes.Item(x).getAttribute("bb")
    Range("A10").Offset(s + 2, 0) = EleXML.ChildNodes.Item(x).getAttribute("cc")
    s = s + 3
Next x

You can figure this out by recording the code.

Sub Macro1()
'
' Macro1 Macro
'

'
    With Selection
        .HorizontalAlignment = xlLeft
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    With Selection
        .HorizontalAlignment = xlRight
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
End Sub

Try this. You can adjust this as per your need.

With Range("A10").Offset(x, 0)
    .HorizontalAlignment = xlLeft
    .VerticalAlignment = xlBottom
    .WrapText = False
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = False
End With

answered May 29, 2013 at 12:44

Santosh's user avatar

SantoshSantosh

12.1k4 gold badges41 silver badges72 bronze badges

1

Понравилась статья? Поделить с друзьями:
  • Vba excel выполнение в фоне
  • Vba excel выпадающий список значения
  • Vba excel выпадающий список в ячейке с поиском
  • Vba excel выпадающий календарь
  • Vba excel вызов подпрограммы