source

Excel 레이블의 캡션에서 텍스트를 세로로 중앙에 배치하려면 어떻게 해야 합니까?

manysource 2023. 6. 19. 21:41

Excel 레이블의 캡션에서 텍스트를 세로로 중앙에 배치하려면 어떻게 해야 합니까?

Excel 2007에서는 워크시트에 ActiveX 레이블을 삽입했습니다.마우스 오른쪽 버튼을 클릭하여 Properties를 보고 TextAlign 속성을 2(frmTextAlignCenter)로 변경했습니다.

이렇게 하면 레이블 캡션의 텍스트가 레이블의 중앙(수평)에 정렬되지만 텍스트는 레이블의 맨 위에 남아 있습니다.캡션 텍스트가 레이블의 중간에 오도록 세로로 중심을 맞추려면 어떻게 해야 합니까?

SO에서 "수직 정렬"을 검색했지만 엑셀 레이블의 캡션에 대한 방법은 나오지 않습니다.

하나의 라벨로 하는 요령이 있습니다.1x1 픽셀의 투명한 gif 이미지(여기)를 추가하고 PictureAlignment 속성을 PicturePositionLeftCenter로 설정합니다.

직접적으로 할 수 있는 방법이 없습니다.하지만 이 게시물은 그것을 성취하는 영리한 방법을 가지고 있습니다.텍스트 주위에 자동 크기의 내부 상자를 두 개 만들고 외부 상자의 중간 지점에 내부 상자를 배치합니다.

저는 단지 상위 투표된 답변에 요약된 접근법을 시도했고 완벽하게 작동했습니다.그러나 접근 방식에 조금 더 추가하기 위해 - 예를 들어 레이블이 많은 경우, 다음을 수행했습니다.

  1. 사용자 양식의 어딘가에 사진 컨트롤을 추가합니다(어디서나 상관 없음).컨트롤의 속성을 다음과 같이 변경합니다.
소유물 가치
이름. GIF
사진. (1x1 투명 gif 사진으로 설정 [link])
보이는 False
  1. 이제 특수 정렬을 수신할 각 레이블 컨트롤에 대해 태그 속성을 변경합니다.
소유물 가치
태그 "LabelAlignmentTheme"
  1. 마지막으로 다음 코드를 추가합니다.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

이 사용법이 마음에 듭니다.Tag그것은 css 스타일처럼 느껴집니다.분명히 당신은 태그에 대한 검사를 건너뛸 수 있고(And 문의 두 번째 부분을 제거함) 절대적으로 모든 것을 정렬할 수 있지만, 저는 이것이 일부만 정렬하기를 원하는 더 현실적인 시나리오라고 생각합니다.

이미지를 양식의 어딘가에 공유된 숨겨진 사진에 저장함으로써 이미지는 파일에 포함됩니다.

두 개의 레이블을 사용해야 합니다.

예를 들어, 레이블 뒤로, 레이블 앞으로를 호출합니다.LabelFront를 불투명 및 경계 없음으로 설정해야 합니다. LabelFront의 높이를 LabelBack의 높이보다 작게 만들고 그 위에 놓아야 합니다.

그런 다음 다음 코드를 추가합니다.

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

내가 뺀 거 알아요1▁the를 보상하기 위해1라벨 전면에 추가 픽셀이 있습니다.

이것은 (수업 중): 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

이 모양은 (모듈 내): 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

언급URL : https://stackoverflow.com/questions/6859127/how-do-i-vertically-center-the-text-in-an-excel-labels-caption