如何动态创建元素的位置?

How to dynamically create an element's position?

我有一个 Outlook 用户表单来显示选定的电子邮件。
由于列表框不能在 column-headers 中包含文本,我采用了建议的解决方案 here

我的问题:

表格初始化后,header-box 位置错误且大小错误。一些检查表明,正确的值由函数 createListboxHeader() 分配 - 并且没有错误。但是在该函数之后检查 header-box 的位置和大小(返回初始化),值是错误的 - 证明我所看到的。

有时它可以正常工作,但大多数时候不能。

代码:

Public Sub createListboxHeader(lstBody As ListBox, arrHeaders)
Dim lstHeader As ListBox
Dim i As Integer

'create new listbox for the header
Set lstHeader = Me.Controls.Add("Forms.ListBox.1","NameOnlyForTesting")

With lstBody
    'ensure properties of body-listbox
    .ColumnHeads = False
    .ZOrder (1)
    .SpecialEffect = fmSpecialEffectFlat
    .BorderStyle = fmBorderStyleSingle
End With

With lstHeader
    'properties of header-listbox
    .BackColor = RGB(200, 200, 200)
    .Enabled = False
    .ZOrder (0)
    .SpecialEffect = fmSpecialEffectFlat
    .BorderStyle = fmBorderStyleSingle

    'make column equal
    .ColumnCount = lstBody.ColumnCount
    .ColumnWidths = lstBody.ColumnWidths

    'add header elements
    .AddItem
    For i = 0 To UBound(arrHeaders)
        .List(0, i) = arrHeaders(i)
    Next i

    'positioning of header-listbox
    .Height = 10
    .Width = lstBody.Width
    .Left = lstBody.Left
    .Top = (lstBody.Top - lstHeader.Height) - 0

    Debug.Print lstBody.Width, lstHeader.Height     ' <-- show both '400'
End With

End Sub

用法:

Private Sub UserForm_Initialize()

'find emails
Dim selEmails As Outlook.Selection
Set selEmails = getSelectedEmails() 'function not displayed here at Whosebug

'show emails in List-Box
Call printSelectedEmailsInList(selEmails)

End Sub


Private Sub printSelectedEmailsInList(selectedEmails As Outlook.Selection)
Dim objEmail As Outlook.MailItem
Dim intCounter  As Integer
Dim arrHeaders() As Variant

With Me.lstSelectedEmails
    'configure listbox
    .Clear
    .ColumnCount = 5
    .ColumnWidths = "70;100;100;200;100"

    'configute header (AFTER body!)
    arrHeaders = Array("Date", "From", "To", "Subject", "Folder")
    Call createListboxHeader(Me.lstSelectedEmails, arrHeaders)
    MsgBox Me.Controls("NameOnlyForTesting").Width             '<-- shows'78' instead of '400'

    'fill list with emails
    intCounter = 0
    For Each objEmail In selectedEmails
        .AddItem
        .List(intCounter, 0) = objEmail.SentOn
        .List(intCounter, 1) = objEmail.SenderName
        .List(intCounter, 2) = objEmail.To
        .List(intCounter, 3) = objEmail.Subject
        .List(intCounter, 4) = objEmail.Parent.Name

        intCounter = intCounter + 1
    Next

End With
End Sub

我通过更改解决了我的问题:

Private Sub UserForm_Initialize()
   [...]
End Sub

至:

Private Sub UserForm_Activate()
   [...]
End Sub