How to add headers to a multicolumn listbox in an Excel userform using VBA

后端 未结 13 2096
[愿得一人]
[愿得一人] 2020-11-30 09:01

Is it possible to set up the headers in a multicolumn listbox without using a worksheet range as the source?

The following uses an array of variants which is assigne

13条回答
  •  悲哀的现实
    2020-11-30 09:52

    Here is my approach to solve the problem:

    This solution requires you to add a second ListBox element and place it above the first one.

    Like this:

    Then you call the function CreateListBoxHeader to make the alignment correct and add header items.

    Result:

    Code:

      Public Sub CreateListBoxHeader(body As MSForms.ListBox, header As MSForms.ListBox, arrHeaders)
                ' make column count match
                header.ColumnCount = body.ColumnCount
                header.ColumnWidths = body.ColumnWidths
    
            ' add header elements
            header.Clear
            header.AddItem
            Dim i As Integer
            For i = 0 To UBound(arrHeaders)
                header.List(0, i) = arrHeaders(i)
            Next i
    
            ' make it pretty
            body.ZOrder (1)
            header.ZOrder (0)
            header.SpecialEffect = fmSpecialEffectFlat
            header.BackColor = RGB(200, 200, 200)
            header.Height = 10
    
            ' align header to body (should be done last!)
            header.Width = body.Width
            header.Left = body.Left
            header.Top = body.Top - (header.Height - 1)
    End Sub
    

    Usage:

    Private Sub UserForm_Activate()
        Call CreateListBoxHeader(Me.listBox_Body, Me.listBox_Header, Array("Header 1", "Header 2"))
    End Sub
    

提交回复
热议问题