Vba – Access subform, how to resize columns to best fit

ms-accessvba

I have a form with a subform. This subform displays the results of a query that is created dynamically (user enters criteria, I build the SQL, then update the querydef and display). Problem is since the columns are dynamic the width of the columns isn't working out, some are cutting off text.

Is there a way to programmatically loop through the columns (or do the same without loop) and set them all to bestfit width after the query is refreshed?

EDIT: Here is what my code looks like now:

CurrentDb.QueryDefs("SearchResults").sql = sql
CurrentDb.QueryDefs.Refresh   

Dim qdf1 As DAO.QueryDef
Dim fld1 As DAO.Field

Set qdf1 = CurrentDb.QueryDefs("SearchResults")

For i = 0 To qdf1.Fields.Count - 1
    Set fld1 = qdf1.Fields(i)
    fld1.CreateProperty "ColumnWidth", dbInteger

    fld1.Properties("ColumnWidth") = -2     'Throws error
    Set fld1 = Nothing
Next i

Me.Child20.SourceObject = "Query.SearchResults"

Best Answer

You can set column widths like so:

Sub SetColumnWidth()
Dim qdf1 As DAO.QueryDef
Dim fld1 As DAO.Field

Set qdf1 = CurrentDb.QueryDefs("query3")

For i = 0 To qdf1.Fields.Count - 1
    Set fld1 = qdf1.Fields(i)
    fld1.CreateProperty "ColumnWidth", dbInteger
    'very narrow indeed
    'fld1.Properties("ColumnWidth") = 200
    'Or -2 : Sizes the column to fit the visible text
    'but it is not quite as useful as it would seem
    fld1.Properties("ColumnWidth") = -2
    Set fld1 = Nothing
Next i

End Sub

See also http://support.microsoft.com/kb/210427

Related Topic