Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need Help with Flex Grid

Status
Not open for further replies.

testeng

Technical User
Apr 5, 2001
32
US
Is there an easy way auto size a MS flex grid like in Excel(EntireColumn.AutoFit) maybe it just me but I can't figure it out. Thanks for your help
 
You can try the following code. I have placed it ibn the flex grids double click event, but you canuse it anywhere.

Private Sub MSFlexGrid1_DblClick()
Const MARGIN = 55 'twips

Dim i As Integer, j As Integer
Dim fieldValueHighText As String
Dim fieldValue As Long
Dim fieldValueHigh As Long

On Error GoTo errHand

txtFloat.Visible = False
fieldValue = 0
fieldValueHigh = 0
For i = 0 To MSFlexGrid1.Cols - 1
fieldValue = 0
fieldValueHigh = 0
For j = 0 To MSFlexGrid1.Rows - 1
fieldValue = Len(MSFlexGrid1.TextMatrix(j, i))
If fieldValue > fieldValueHigh Then
fieldValueHigh = fieldValue
fieldValueHighText = MSFlexGrid1.TextMatrix(j, i)
End If
Next j
fieldValueHigh = PixelsToTwipsX(FindTextWidthInPixels(fieldValueHighText, 8, "MS Sans Serif", False))
MSFlexGrid1.ColWidth(i) = (MARGIN * 2) + fieldValueHigh
Next i
Exit Sub

errHand:
MsgBox Err.Description
End Sub

Private Function FindTextWidthInPixels(Msg As String, Optional FSize As Integer = 8, Optional TheFont As String = "MS Sans Serif", Optional Bold As Boolean = False) As Single
Dim F As StdFont, S As Integer

S = Me.ScaleMode
Me.ScaleMode = vbPixels
Set F = Me.Font
Me.FontBold = Bold
Me.FontSize = FSize
Me.Font = TheFont
FindTextWidthInPixels = Me.TextWidth(Msg)
Me.Font = F
Me.ScaleMode = S
End Function

Function PixelsToTwipsX(Pixels As Long) As Long
PixelsToTwipsX = Pixels * Screen.TwipsPerPixelX
End Function

You can adjust the MARGIN constant as you need to place the text.

Thanks and Good Luck!

zemp
 
One more thing, you can remove the following after the On Error statement, They are specific to my program or not needed.

txtFloat.Visible = False
fieldValue = 0
fieldValueHigh = 0
Thanks and Good Luck!

zemp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top