1、在工作表“Sheet1”里,命令按鈕點(diǎn)擊事件,顯示用戶窗體UserForm1: Private Sub CmdShowUserForm_Click() UserForm1.ShowEnd Sub 2、在myModule 里,自動(dòng)設(shè)置ListView列寬過程,有3個(gè)選項(xiàng),代碼中均有注釋,根據(jù)實(shí)際情況選擇:Private Declare PtrSafe Function SendMessage Lib "user32" _ Alias "SendMessageA" ( _ ByVal hwnd As LongPtr, _ ByVal wMsg As LongPtr, _ ByVal wParam As LongPtr, _ ByVal lParam As LongPtr) As LongPtr Private Const LVM_FIRST As LongPtr = &H1000 Private Const LVM_SETCOLUMNWIDTH As LongPtr = LVM_FIRST + 30 Private Const LVSCW_AUTOSIZE As LongPtr = -1 Private Const LVSCW_AUTOSIZE_USEHEADER As LongPtr = -2
Sub AutoResizeListViewColumn(lv As ListView, Optional AutoSizeType As Integer = 1) '函數(shù)用于自動(dòng)調(diào)整ListView列寬 With lv If AutoSizeType = 1 Then '//根據(jù)標(biāo)題與內(nèi)容寬度調(diào)整,均完整顯示,最適合列寬 SendMessage .hwnd, LVM_SETCOLUMNWIDTH, .ColumnHeaders.Count - 1, ByVal LVSCW_AUTOSIZE_USEHEADER For i = 0 To .ColumnHeaders.Count - 2 SendMessage .hwnd, LVM_SETCOLUMNWIDTH, i, ByVal LVSCW_AUTOSIZE_USEHEADER Next ElseIf AutoSizeType = 2 Then '//根據(jù)標(biāo)題與內(nèi)容寬度調(diào)整,均完整顯示,如果所有列寬之和小于ListView的寬度,最后一列占有剩余寬度 For i = 0 To .ColumnHeaders.Count - 1 SendMessage .hwnd, LVM_SETCOLUMNWIDTH, i, ByVal LVSCW_AUTOSIZE_USEHEADER Next Else '//根據(jù)內(nèi)容寬度調(diào)整,標(biāo)題有可能不完全顯示 For i = 0 To .ColumnHeaders.Count - 1 SendMessage .hwnd, LVM_SETCOLUMNWIDTH, i, ByVal LVSCW_AUTOSIZE Next End If End With End Sub 3、在UserForm1里,用戶窗體Activate事件,給ListView添加表頭、內(nèi)容,根據(jù)Checkbox1(自動(dòng)列寬)的值,確定是否調(diào)用自動(dòng)列寬過程,最后,根據(jù)ListView的寬度,調(diào)整用戶窗體的寬度,再根據(jù)用戶窗體的寬度,調(diào)整標(biāo)題標(biāo)簽位置始終居中:Private Sub UserForm_Activate() Dim LvItem As ListItem Dim ws As Worksheet Dim ckb As OLEObject Dim iWidth As Single '//設(shè)置ListView With Me.LvDetail '//ListView的基本設(shè)置 .View = lvwReport 'listview控件的顯示外觀,需要自動(dòng)調(diào)整列寬的,此項(xiàng)為必須 .Gridlines = True .Sorted = False .CheckBoxes = True .LabelEdit = lvwManual '//添加表頭 .FullRowSelect = True For i = 1 To 6 .ColumnHeaders.Add , , "標(biāo)題" & i, 80 Next '//添加內(nèi)容 For i = 1 To 10 Set LvItem = .ListItems.Add LvItem.Text = i For j = 1 To 5 LvItem.SubItems(j) = "內(nèi)容" & Space(j * 2) & j + 1 Next Next End With '//根據(jù)checkBox的值決定是否自動(dòng)列寬 Set ws = ThisWorkbook.Sheets("Sheet1") Set ckb = ws.OLEObjects("CheckBox1") If ckb.Object.Value = True Then Call AutoResizeListViewColumn(LvDetail, 1) 'Call AutoResizeListViewColumn(LvDetail, 2) 'Call AutoResizeListViewColumn(LvDetail, 3) End If '//調(diào)整ListView的寬度與窗體的寬度 With Me.LvDetail '//計(jì)算總寬度 For i = 1 To .ColumnHeaders.Count iWidth = iWidth + .ColumnHeaders(i).Width Next .Width = iWidth + 5 '//根據(jù)ListView的寬度調(diào)整窗體的寬度 Me.Width = .Left + .Width + 20 '//調(diào)整標(biāo)題標(biāo)簽位置,始終居中 Me.Label1.Left = (Me.Width - Me.Label1.Width) / 2 End WithEnd Sub
|