代碼如下,應該蠻多人也會做,
Public Function AutoFitWidth(ByRef dg As DataGrid) As Boolean
Dim rsData As ADODB.Recordset
If rsData Is Nothing Then Exit Function
If rsData.State = 0 Then Exit Function
If rsData.RecordCount = 0 Then Exit Function
Dim celltext As String
Dim celltext1 As String
'Dim Maxwidth As Single
Dim m As Integer, i As Integer
Dim width As Single
'Maxwidth = 0
For m = 0 To rsData.Fields.Count - 1
'celltext = dg.Columns(m).Text
celltext = dgRef.Columns(m).Caption
width = dgRef.Parent.TextWidth(celltext) '列標題的寬度
rsData.MoveFirst '第一條記錄
For i = 0 To rsData.RecordCount - 1
celltext1 = rsData.Fields(m)
If dgRef.Parent.TextWidth(celltext1) > width Then '取最大的欄位長度,其實是自身比較大小
width = dgRef.Parent.TextWidth(celltext1)
End If
rsData.MoveNext
Next i
dgRef.Columns(m).width = width + 200 '然后再賦值,設定成最大寬度
Next m '移到第二個欄位
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/91002.html
標籤:控件
