I have a UserForm that uses a ListView
control (from Microsoft Common Controls).
To autosize the columns of this ListView
I use the following WinAPI call within the UserForm, which works fine and correctly sets the size of the column:
Private Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As LongPtr, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As LongPtr
Private Const LVM_FIRST = &H1000
Private Const LVM_SETCOLUMNWIDTH = (LVM_FIRST + 30)
Private Const LVSCW_AUTOSIZE_USEHEADER = -2
Private Sub UserForm_Initialize()
'Autosizes the first column of the ListView
SendMessage ListView.hWnd, LVM_SETCOLUMNWIDTH, 0, LVSCW_AUTOSIZE_USEHEADER
End Sub
However, if I hide and then re-show the UserForm (e.g. using Me.Hide
and Me.Show
in a CommandButton
event) this WinAPI call goes wrong and sets the column width to ~16,000 pixels.
I assume the error is because the hWnd
of the ListView
and/or UserForm itself is changed after the hide and show.
Is anyone aware of a fix for this issue?