Public Sub FlexGrid_AutoSizeColumns(ByRef pGrid As MSFlexGrid, _
ByRef pForm As Form, _
Optional ByVal pIncludeHeaderRows As Boolean = True, _
Optional ByVal pAllowShrink As Boolean = True, _
Optional ByVal pMinCol As Long = 0, _
Optional ByVal pMaxCol As Long = -1, _
Optional ByVal pBorderSize As Long = 8)
'Set flexgrid column widths to the minimum for viewing all text
'Note that this will not be accurate if Cells have different fonts,
'or if .FontWidth (or .CellFontWidth) has been set
'Parameters:
' pGrid - the grid to work with
' pForm - the form the grid is on
' pIncludeHeaderRows - whether to take the width of text in FixedRows into account
' pAllowShrink - allow column widths to get smaller than current?
' pMinCol - the first column to work with
' pMaxCol - the last column to work with (-1 means the right-most column)
' pBorderSize - the number of pixels used as a border around text (seems like 8 to me!)
Dim lngMinCol As Long, lngMaxCol As Long, lngCurrRow As Long
Dim lngMinRow As Long, lngMaxRow As Long, lngCurrCol As Long
Dim lngMaxWidth As Long, lngCurrWidth As Long
Dim fntFormFont As StdFont
'Store current form font (so can restore later)
Set fntFormFont = New StdFont
Call CopyFont(pForm.Font, fntFormFont)
'Set font of form to same as grid, to get accurate values
Call CopyFont(pGrid.Font, pForm.Font)
With pGrid 'Set rows/columns to check
lngMinCol = pMinCol
lngMaxCol = IIf(pMaxCol = -1, .Cols - 1, pMaxCol)
lngMinRow = IIf(pIncludeHeaderRows, 0, .FixedRows)
lngMaxRow = .Rows - 1
'For each column in specified range..
For lngCurrCol = lngMinCol To lngMaxCol
'..set min allowed size based on options
lngMaxWidth = IIf(pAllowShrink, 0, pForm.ScaleX(.ColWidth(lngCurrCol), vbTwips, pForm.ScaleMode))
For lngCurrRow = lngMinRow To lngMaxRow '..find widest text (in scalemode of the form)
lngCurrWidth = pForm.TextWidth(.TextMatrix(lngCurrRow, lngCurrCol))
If lngMaxWidth < lngCurrWidth Then lngMaxWidth = lngCurrWidth
Next lngCurrRow
'..as the scalemode of the form may differ, convert to twips
lngMaxWidth = pForm.ScaleX(lngMaxWidth, pForm.ScaleMode, vbTwips)
'..resize the column as apt (with specified border size)
.ColWidth(lngCurrCol) = lngMaxWidth + (pBorderSize * Screen.TwipsPerPixelX)
Next lngCurrCol
End With
'Restore form font
Call CopyFont(fntFormFont, pForm.Font)
End Sub
Public Sub CopyFont(ByVal pFontFrom As StdFont, ByRef pFontTo As StdFont)
'Copy the properties of a font object to another
With pFontFrom
pFontTo.Bold = .Bold
pFontTo.Charset = .Charset
pFontTo.Italic = .Italic
pFontTo.Name = .Name
pFontTo.Size = .Size
pFontTo.Strikethrough = .Strikethrough
pFontTo.Underline = .Underline
pFontTo.Weight = .Weight
End With
End Sub