VB and VBA Users Source Code: Auto-resizing the columns in a listview
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Auto-resizing the columns in a listview
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Tuesday, May 13, 2003
Hits:
1571
Category:
Windows API
Article:
The code below shows how to autofit the column widths of a listview. Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long 'Purpose : Autosizes the specified columns in a listview 'Inputs : oLV The listview to autosize the columns. ' [lStartCol] The first column autosize (defaults to the first column) ' [lEndCol] The first last column to autosize (defaults to the last column) ' [lMaxColWidth] The max. column width ' [bIncludeHeading] If True includes the column heading text when resizing 'Outputs : Returns True on success 'Author : Andrew Baker 'Date : 25/11/2000 03:17 'Notes : 'Revisions : Function LVAutosizeCols(oLV As ListView, Optional lStartCol As Long = 0, Optional lEndCol As Long = -1, Optional lMaxColWidth As Long = 0, Optional bIncludeHeading As Boolean = True) As Boolean Const LVM_FIRST As Long = 4096, LVM_SETCOLUMNWIDTH = (LVM_FIRST + 30) Const LVSCW_AUTOSIZE As Long = -1, LVSCW_AUTOSIZE_USEHEADER As Long = -2 Dim lRtn As Long, lParam As Long, lThisCol As Long On Error GoTo ErrFailed 'Determine type of autosizing If bIncludeHeading Then lParam = LVSCW_AUTOSIZE_USEHEADER Else lParam = LVSCW_AUTOSIZE End If 'Determine the last column to resize If lEndCol = -1 Then lEndCol = oLV.ColumnHeaders.Count - 1 End If 'Autosize columns For lThisCol = lStartCol To lEndCol lRtn = SendMessage(oLV.hwnd, LVM_SETCOLUMNWIDTH, lThisCol, ByVal lParam) If lMaxColWidth Then 'Check column doesn't exceed max width If oLV.ColumnHeaders(lThisCol + 1).Width > lMaxColWidth Then oLV.ColumnHeaders(lThisCol + 1).Width = lMaxColWidth End If End If Next If lRtn <> 0 Then 'Return Success LVAutosizeCols = True End If Exit Function ErrFailed: Debug.Print Err.Description Debug.Assert False LVAutosizeCols = False End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder