【问题标题】:VBA: How go I get the total width from all controls in an MS-Access form?VBA:如何从 MS-Access 表单中的所有控件中获取总宽度?
【发布时间】:2010-04-24 02:50:32
【问题描述】:

这可能是非常基本的东西,但请记住我对这些东西完全陌生。

我正在为我的 Access 数据表表单制定一个程序,该程序将:

  1. 调整每列的宽度以适应内容
  2. 将所有列的总宽度相加并从窗口宽度的大小中减去
  3. 调整其中一列的宽度以适应剩余空间

这是调整每列宽度以适应内容的代码(效果很好):

Dim Ctrl As Control
Dim Path As String
Dim ClmWidth As Integer

'Adjust column width to fit content
For Each Ctrl In Me.Controls
    If TypeOf Ctrl Is TextBox Then
        Path = Ctrl.Name
        Me(Path).ColumnWidth = -2
    End If
Next Ctrl

我应该如何编写代码以获得所有列的总宽度?

非常感谢!

斯蒂芬

解决方案


这是使 Access 数据表从此开始的代码:

alt text http://bayimg.com/image/galphaacp.jpg

到这里:

alt text http://bayimg.com/image/galpnaacp.jpg

Sub AdjustColumnWidth(frm As Form, clm As String)

On Error GoTo HandleError

Dim intWindowWidth As Integer   ' Window width property
Dim ctrl As Control             ' Control
Dim intCtrlWidth As Integer     ' Control width property
Dim intCtrlSum As Integer       ' Control width property sum
Dim intCtrlAdj As Integer       ' Control width property remaining after substracted intCtrSum

'Adjust column width to standard width
For Each ctrl In frm.Controls
    If TypeOf ctrl Is TextBox Or TypeOf ctrl Is CheckBox Or TypeOf ctrl Is ComboBox Then
        Path = ctrl.Name
        frm(Path).ColumnWidth = 1500
    End If
Next ctrl

'Get total column width
For Each ctrl In frm.Controls
    If TypeOf ctrl Is TextBox Or TypeOf ctrl Is CheckBox Or TypeOf ctrl Is ComboBox Then
        Path = ctrl.Name
        intCtrlWidth = frm(Path).ColumnWidth
        If Path <> clm Then
            intCtrlSum = intCtrlSum + intCtrlWidth
        End If
    End If
Next ctrl

'Adjust column to fit window
intWindowWidth = frm.WindowWidth - 270
intCtrlAdj = intWindowWidth - intCtrlSum
frm.Width = intWindowWidth
frm(clm).ColumnWidth = intCtrlAdj

Debug.Print "Totalt (Ctrl): " & intCtrlSum
Debug.Print "Totalt (Window): " & intWindowWidth
Debug.Print "Totalt (Remaining): " & intCtrlAdj
Debug.Print "clm : " & clm

HandleError:
GeneralErrorHandler Err.Number, Err.Description
Exit Sub

End Sub

调用程序的代码:

Private Sub Form_Load()

Call AdjustColumnWidth(Me, "txtDescription")

End Sub

【问题讨论】:

    标签: ms-access vba width datasheet


    【解决方案1】:

    我将像您之前所做的那样遍历表单控件集合,并通过将宽度存储在变量中来相加。你甚至可以将它添加到你现有的循环中,这样你就不会循环两次,只需执行类似的操作

    sTotal_width=sTotal_width + Ctrl.Width
    

    【讨论】:

    • 谢谢你,这很有意义!