How to Set Column Width in Datasheet View?

Steve R.

Retired
Local time
Today, 16:31
Joined
Jul 5, 2006
Messages
5,266
I have a subform that is in datasheet view. Through testing, I found that the using
Code:
Me.TYPE5SUBFRM.Form.projectname.Width
returns the width of the control itself on the subform, not the displayed width of the datasheet column.

How would I be able to reference the displayed datasheet column width?
 
not sure how to get the width, but you can set the width to match the contents on Form_Current event:
me.Ctl1.columnwidth = -2
me.Ctl2.columnwidth = -2
etc
 
Thanks, I found the reference to "ColumnWidth" in ACCESS help, now I have to figure it out.

According to MS
----------------------------------------------------------------------------
"RowHeight, ColumnWidth Properties Example

The following example changes the row height in Datasheet view of the Customers table to display two lines of data (450 twips) and sets the width of the Address column to 1.5 inches (2160 twips). These property settings will take effect the next time the Customers table is opened in Datasheet view.

To set the RowHeight and ColumnWidth properties, the example uses the SetTableProperty procedure, which is shown in the example for the DatasheetFontItalic and DatasheetFontUnderline properties, and the SetFieldProperty procedure, which is shown in the example for the ColumnHidden property.

Dim dbs As Object, tdfCustomers As Object
Const DB_Long As Long = 4
Const DB_Integer As Integer = 3
Set dbs = CurrentDb
Set tdfCustomers = dbs![Customers]
SetTableProperty tdfCustomers, "RowHeight", DB_Long, 450
SetFieldProperty tdfCustomers![Address], "ColumnWidth", DB_Integer, 2160
The next example takes effect in Datasheet view of the open Customers form. It sets the row height to 450 twips and sizes the column to fit the size of the visible text.

Forms![Customers].RowHeight = 450
Forms![Customers]![Address].ColumnWidth = -2
 
Also, if you load this code on the on current event of your main form the columns will adjust to the data within them.

Me.YourSubformControlNameHere.Form.ControlName.ColumnWidth = -2

Place this code for each control

This solution was presented to me from boblarson. Thanks Bob
 
i'm new to Access , could you please explain.
I click on a command buttom and the datasheet displays.
Where would I put this code?
 
Since this is an old thread, I would suggest posting this as a new question if my response does not address your concerns

Check-out Access help, press F1.

Use "Alt F11" to access the VBA pane for that form. In the Open event you can have this code to establish the width of the form.
Code:
Private Sub Form_Open(Cancel As Integer)    
    Me.ScrollBars = 3
    Me.Form.Width = 15840
End Sub

On the Form Current Event, I have the following. The function PrintFormWidth is used to print the column widths for testing purposes.
Code:
Private Sub Form_Current()
    On Error GoTo ERR_Form_Current
    Rem Call PrintFormWidth
    Me.PermitNumber02.ColumnWidth = 1020
    Me.InspectionDate02.ColumnWidth = 1245
    Me.AddressLocation02.ColumnWidth = 2730
    Me.CountyName02.ColumnWidth = 1450
    Me.Permittee02.ColumnWidth = 2775
    If Me.Parent.Text25 <= 21 Then 'Scroll Bar Adjustment
            Me.Comments02.ColumnWidth = 6200
        Else
            Me.Comments02.ColumnWidth = 5960
        End If
    Me.Parent.Text30 = Me.RecordIDnum02
    Exit Sub
ERR_Form_Current:
    Resume Next
End Sub


The code below is for testing, it is not part of the production code.
Code:
Private Sub PrintFormWidth()
    Rem this is meant as a form development utility.
    Rem NOT meant to run each time the form opens.
    Dim intSubTotal As Long
    Dim intFormWidth As Integer
    Dim intCol1 As Integer
    Dim intCol2 As Integer
    Dim intCol3 As Integer
    Dim intCol4 As Integer
    Dim intCol5 As Integer
    Dim intCol6 As Integer
    Dim intCol7 As Integer
    Dim intCol8 As Integer
    Dim intCol9 As Integer
    Rem Width of Vertical Scrollbar = 240
    intFormWidth = Me.Width
    intCol1 = Me.PermitNumber02.ColumnWidth
    intCol2 = Me.InspectionDate02.ColumnWidth
    intCol3 = Me.AddressLocation02.ColumnWidth
    intCol4 = Me.CountyName02.ColumnWidth
    intCol5 = Me.Permittee02.ColumnWidth
    intCol6 = Me.Comments02.ColumnWidth
    intCol7 = Me.RecordIDnum02.ColumnWidth
    Debug.Print "Column 1 Width: ", intCol1
    Debug.Print "Column 2 Width: ", intCol2
    Debug.Print "Column 3 Width: ", intCol3
    Debug.Print "Column 4 Width: ", intCol4
    Debug.Print "Column 5 Width: ", intCol5
    Debug.Print "Column 6 Width: ", intCol6
    Debug.Print "Column 7 Width: ", intCol7
    intSubTotal = intCol1 + intCol2 + intCol3 + intCol4 + intCol5 + intCol6 + intCol7
    Debug.Print "Form Width:     "; intFormWidth
    Debug.Print "Width SubTotal: "; intSubTotal
    Me.Width = intSubTotal
End Sub
 
I have spent years trying to change the size of the datasheet fields in a subform or form and have always been unsuccessful. I've tried everything on this page and and many others. Absolutely nothing works. Currently I would love to be able to this on a subform in Access 2010.
 
Hi Terry

I hope you have found your solution but just in case you haven't....

This works for me in Access 2010
Add the following to the form_open code for my sub form for each field:
me.<fieldName>.ColumnWidth = -2

Thanks to the post from jleval

The fieldname I used is the text box name, for my db this is different to the actual field name in the table.

It's a bit cumbersome to repeat the line for each field but it works.
Could probably put in a loop but there are not so many fields in my sub form.

Ron
 
I know this is an old thread, but I've had success by just adjusting the column widths in Layout View and then saving the form. That seems to work for me.
 
[FONT=&quot]I found the following to work for me:[/FONT]

  1. [FONT=&quot]Open the form that has all of the subforms on it.[/FONT]
  2. [FONT=&quot]re-arrange or size the fields in the subforms as you wish them to be - change the sorting order on columns if you wish as well
    [/FONT]
  3. [FONT=&quot]click on (highlight) one of the columns in the subform[/FONT]
  4. [FONT=&quot]on the ribbon, in the text formatting group, center this column (or change any attribute in the text formatting group), then change it back to left justified (or Bold and then un-bold the subform)[/FONT]
  5. [FONT=&quot]Now - close the form, you will be prompted to save your forms, do so[/FONT]
[FONT=&quot]Apparently Access doesn't recognize changes to the column width as something to change, but if you combine with anything in the formatting group, it will save the column widths / positions, sorting as well.[/FONT]
[FONT=&quot]
[/FONT]
[FONT=&quot]Has worked for me without fail[/FONT]
 
This thread keeps getting resurected! I recently wrote a module to set column width, order, and hidden properties based solely on the control's tag. It can also save column width and order adjustments made by the end user in the front end. I'll post it once I get back home.
 
Sorry, forgot about this. It seems to work great, but I haven't completely tested it.

Code:
Option Compare Database
Option Explicit

Private booDebug As Boolean

Private Sub SetDebug()
    booDebug = False
End Sub

Public Sub SetDefaultColumnInfo(frm As Form)
    On Error GoTo err
    
    SetDebug
    Dim booPercentage As Boolean
    
    Dim strArray() As String
    Dim i As Integer
    Dim strDummy As String
    
    strArray = Split(frm.Tag, ";")
    For i = LBound(strArray) To UBound(strArray)
        If Left(strArray(i), 4) = "RowH" Then
            If Right(strArray(i), 1) = "%" Then
                strDummy = Right(strArray(i), Len(strArray(i)) - 5)
                strDummy = Left(strDummy, Len(strDummy) - 1)
                frm.RowHeight = CDbl("." & strDummy) * frm.InsideHeight
            Else
                frm.RowHeight = CInt(Right(strArray(i), Len(strArray(i)) - 5))
            End If
        End If
        If Left(strArray(i), 5) = "FontH" Then
            frm.DatasheetFontHeight = CInt(Right(strArray(i), Len(strArray(i)) - 6))
        End If
    Next
    
    Dim ctl As Control
    Dim lngW As Long
    
    lngW = frm.InsideWidth - 2 * 270    '270 for the recordselectors and scroll bar
    
    For Each ctl In frm.Controls
        Select Case ctl.ControlType
            Case acCheckBox, acComboBox, acTextBox
                strArray = Split(ctl.Tag, ";")
                For i = LBound(strArray) To UBound(strArray)
                    Select Case Left(strArray(i), 2)
                        Case "H="
                            If Right(strArray(i), 1) = "1" Then ctl.ColumnHidden = True
                            If Right(strArray(i), 1) = "0" Then ctl.ColumnHidden = False
                        Case "O="
                            ctl.ColumnOrder = Right(strArray(i), Len(strArray(i)) - 2)
                        Case "W="
                            If Right(strArray(i), 1) = "%" Then
                                'this must be done at the end since it is a percentage
                                booPercentage = True
                            Else
                                lngW = lngW - Right(strArray(i), Len(strArray(i)) - 2)
                                ctl.ColumnWidth = Right(strArray(i), Len(strArray(i)) - 2)
                            End If
                        Case Else
                            If booDebug Then Debug.Print "unhandled case: " & strArray(i)
                    End Select
                Next
            Case acLabel
            Case Else
                If booDebug Then Debug.Print "unhandled case: " & ctl.ControlType
        End Select
    Next
    
    If booPercentage Then DoItAgain frm, lngW
    
    Exit Sub
err:
    If booDebug Then Debug.Print "SetDefaultColumnInfo " & err.Number & ": " & err.Description
End Sub

Private Sub DoItAgain(frm As Form, lngW As Long)
    On Error GoTo err
    
    Dim strArray() As String
    Dim i As Integer
    Dim strDummy As String
    
    Dim ctl As Control
    
    For Each ctl In frm.Controls
        Select Case ctl.ControlType
            Case acCheckBox, acComboBox, acTextBox
                strArray = Split(ctl.Tag, ";")
                For i = LBound(strArray) To UBound(strArray)
                    Select Case Left(strArray(i), 2)
                        Case "W="
                            If Right(strArray(i), 1) = "%" Then
                                If InStr(1, ctl.Tag, "H=1") Then GoTo skip
                                strDummy = Left(strArray(i), Len(strArray(i)) - 1)
                                strDummy = Right(strDummy, Len(strDummy) - 2)
                                ctl.ColumnWidth = CDbl("." & strDummy) * lngW
skip:
                            End If
                    End Select
                Next
            Case acLabel
            Case Else
                If booDebug Then Debug.Print "unhandled case: " & ctl.ControlType
        End Select
    Next
    
    
    Exit Sub
err:
    If booDebug Then Debug.Print "DoItAgain: " & err.Number & ": " & err.Description
End Sub


Public Sub SaveColumnInfo(frm As Form)
    On Error GoTo err
    
    SetDebug
    
    Dim strTableName As String
    strTableName = "tbl" & frm.Name
    
    If Not TableExists(strTableName) Then CreateColumnInfoTable frm
    
    Dim db As Database
    Dim rst As DAO.Recordset
    
    Set db = CurrentDb
    Set rst = db.OpenRecordset(strTableName)

    rst.MoveFirst
    rst.Edit

    Dim ctl As Control
    For Each ctl In frm.Controls
        Select Case ctl.ControlType
            Case acCheckBox, acComboBox, acTextBox
                rst(ctl.Name & "H") = ctl.ColumnHidden
                rst(ctl.Name & "O") = ctl.ColumnOrder
                rst(ctl.Name & "W") = ctl.ColumnWidth
            Case acLabel
            Case Else
                If booDebug Then Debug.Print "unhandled case: " & ctl.ControlType
        End Select
    Next
     
    rst("RowH") = frm.RowHeight
    rst("FontH") = frm.DatasheetFontHeight

    rst.Update
    
clean:
    On Error Resume Next
    rst.Close
    Set rst = Nothing
    Set db = Nothing
    
    Exit Sub
err:
    If err.Number = 3021 Then 'no current record
        rst.AddNew
        rst.Update
        rst.MoveFirst
        Resume Next
    Else
        If booDebug Then Debug.Print "SaveColumnInfo: " & err.Number & " " & err.Description
        Resume clean
    End If
End Sub


Public Sub LoadColumnInfo(frm As Form)

    On Error GoTo err

    SetDebug
    
    Dim booDeleteTable As Boolean
    
    Dim strTableName As String
    strTableName = "tbl" & frm.Name
    
    If Not TableExists(strTableName) Then CreateColumnInfoTable frm

    Dim db As Database
    Dim rst As DAO.Recordset
    
    Set db = CurrentDb
    Set rst = db.OpenRecordset(strTableName)
    
    Dim ctl As Control
    For Each ctl In frm.Controls
        Select Case ctl.ControlType
            Case acCheckBox, acComboBox, acTextBox
                ctl.ColumnOrder = rst(ctl.Name & "O")
                ctl.ColumnWidth = rst(ctl.Name & "W")
                ctl.ColumnHidden = rst(ctl.Name & "H")
            Case acLabel
            Case Else
                If booDebug Then Debug.Print "unhandled case: " & ctl.ControlType
        End Select
    Next
    
    frm.RowHeight = rst("RowH")
    frm.DatasheetFontHeight = rst("FontH")
    
clean:
    On Error Resume Next
    rst.Close
    Set rst = Nothing
    Set db = Nothing
    If booDeleteTable Then
        DoCmd.DeleteObject acTable, strTableName
        db.TableDefs.Refresh
        RefreshDatabaseWindow
    End If
    Exit Sub
err:
    If booDebug Then Debug.Print "LoadColumnInfo: " & err.Number & ": " & err.Description
    If err.Number = 3265 Then booDeleteTable = True 'item not found in this collection, delete table to be rebuild later
    Resume clean
End Sub



Private Function TableExists(strName As String) As Boolean
    On Error GoTo err
    TableExists = IsObject(CurrentDb.TableDefs(strName))
err:
End Function

Private Sub CreateColumnInfoTable(frm As Form)
    On Error GoTo err
    
    Dim db As Database
    Dim tbl As TableDef
    Dim fld As Field
    Dim ctl As Control
    
    Set db = CurrentDb
    Set tbl = db.CreateTableDef("tbl" & frm.Name)
    
    For Each ctl In frm.Controls
        Select Case ctl.ControlType
            Case acCheckBox, acComboBox, acTextBox
                Set fld = tbl.CreateField(ctl.Name & "O", dbInteger)
                tbl.Fields.Append fld
                Set fld = tbl.CreateField(ctl.Name & "W", dbLong)
                tbl.Fields.Append fld
                Set fld = tbl.CreateField(ctl.Name & "H", dbInteger)
                tbl.Fields.Append fld
            Case acLabel
            Case Else
                If booDebug Then Debug.Print "unhandled case: " & ctl.ControlType
        End Select
        
    Next
    
    Set fld = tbl.CreateField("RowH", dbLong)
    tbl.Fields.Append fld
    Set fld = tbl.CreateField("FontH", dbInteger)
    tbl.Fields.Append fld

    db.TableDefs.Append tbl
    db.TableDefs.Refresh
    RefreshDatabaseWindow
clean:
    On Error Resume Next
    Set db = Nothing
    Set tbl = Nothing
    Set fld = Nothing
    Exit Sub
err:
    If booDebug Then Debug.Print "CreateColumnInfoTable: " & err.Number & " " & err.Description
    Resume clean
End Sub

And in your datasheet form:

Code:
Private Sub Form_Resize()
    SetDefaultColumnInfo Me
    LoadColumnInfo Me
End Sub

Private Sub Form_Unload(Cancel As Integer)
    SaveColumnInfo Me
End Sub
 
[FONT=&quot]I found the following to work for me:[/FONT]

  1. [FONT=&quot]Open the form that has all of the subforms on it.[/FONT]
  2. [FONT=&quot]re-arrange or size the fields in the subforms as you wish them to be - change the sorting order on columns if you wish as well
    [/FONT]
  3. [FONT=&quot]click on (highlight) one of the columns in the subform[/FONT]
  4. [FONT=&quot]on the ribbon, in the text formatting group, center this column (or change any attribute in the text formatting group), then change it back to left justified (or Bold and then un-bold the subform)[/FONT]
  5. [FONT=&quot]Now - close the form, you will be prompted to save your forms, do so[/FONT]
[FONT=&quot]Apparently Access doesn't recognize changes to the column width as something to change, but if you combine with anything in the formatting group, it will save the column widths / positions, sorting as well.[/FONT]
[FONT=&quot]
[/FONT]
[FONT=&quot]Has worked for me without fail[/FONT]

This worked for me too. Thanks so much BMiles13! This has been bugging for for longer than I care to mention :D
 
After a few hours... A number of databases with many tables and many forms and trying to find the way to adjust select column widths and this is the answer for me. Access 2013. With me, no access to any ribbon modifications. Used right-button Conditional Formatting. After setting width, reversed the formatting and it worked.

Thank you!
 
[FONT=&quot]I found the following to work for me:[/FONT]

  1. [FONT=&quot]Open the form that has all of the subforms on it.[/FONT]
  2. [FONT=&quot]re-arrange or size the fields in the subforms as you wish them to be - change the sorting order on columns if you wish as well
    [/FONT]
  3. [FONT=&quot]click on (highlight) one of the columns in the subform[/FONT]
  4. [FONT=&quot]on the ribbon, in the text formatting group, center this column (or change any attribute in the text formatting group), then change it back to left justified (or Bold and then un-bold the subform)[/FONT]
  5. [FONT=&quot]Now - close the form, you will be prompted to save your forms, do so[/FONT]
[FONT=&quot]Apparently Access doesn't recognize changes to the column width as something to change, but if you combine with anything in the formatting group, it will save the column widths / positions, sorting as well.[/FONT]
[FONT=&quot]
[/FONT]
[FONT=&quot]Has worked for me without fail[/FONT]

OMG you are a darn genius. I have always struggled with this, and there was never a clear solution. This solution gets to the heart of an issue. They didn't account for the direct changing of column width in data sheet view, but account for it, when saving other formatting changes. So brilliant!

Thanks for posting this!:D
 
Hi,

I came across same issue today and found solution on this link.

For anybody else having same issue, use following code (I modified the code a little because original code from the above mentioned post saves column width of only text boxes but my form had combo boxes too, column width of which was not getting saved) in close and open events of your subform respectively and then open main form in Form View and then manually select desired widths either by mouse, by entering column width value or using best fit. Save the form and reopen to check results.

Rich (BB code):
Private Sub Form_Close()
        Dim ctrl As Control
      
        For Each ctrl In Me.Controls
            If (ctrl.ControlType = acTextBox Or ctrl.ControlType = acComboBox) Then
                SaveSetting "propertiesDBS", Me.Name, ctrl.Name, ctrl.ColumnWidth
            End If
        Next
    End Sub


Rich (BB code):
Private Sub Form_Open(Cancel As Integer)
    Dim ctrl As Control
    Dim frm As Form
    Dim w As Long
        For Each ctrl In Me.Controls
            If (ctrl.ControlType = acTextBox Or ctrl.ControlType = acComboBox) Then
                w = GetSetting("propertiesDBS", Me.Name, ctrl.Name, 0)
                If w <> 0 Then ctrl.ColumnWidth = w
            End If
        Next
    End Sub
 
Last edited:

Users who are viewing this thread

Back
Top Bottom